How can I programatically set select a list value?

We switched the STATE input box to a select list which was populated from the data.

We need to extract it from a combined field as illustrated below.

I’m need to know how to set the the select list value to the STATE code.

I think setting the “selected” attribute is what you’re looking for:

results.attr("value","myState");
results.attr("selected","selected");

It sounded correct, but didn’t produce the desired result.

Sorry, pulled the trigger a little too quickly on that one. Here’s a script that should work. Assuming that your variable myState now contains the proper state and that results points to the dropdown box:

opts = results.children();
for(var i=0;i<opts.length;i++){
 if(opts[i].attr("value")==myState){
  opts[i].attr("selected","selected");
 } else {
  opts[i].removeAttr("selected");
 }
}

or, more elegant and compact:

opts = results.children();
opts.each(function(index,opt){
 if(opt.attr("value")==myState){
  opt.attr("selected","selected");
 } else {
  opt.removeAttr("selected");
 }
});

NOTE: This comment is referring to the comment prior to the modified code

With this I get the state value set as “OH”

results.attr("value","myState");
<select value="OH" id="selW9State" name="selW9State" required="">

With this I get the state value set as "OH" and "selected=selected"
results.attr("value","myState");
results.attr("selected","selected");
<select selected="selected" value="OH" id="selW9State" name="selW9State" required="">
However shouldn't the selected be
<option value="">--</option>
<option value="NV">NV</option>
<option value="NY">NY</option>
<option value="OH" selected>OH</option>
<option value="OK">OK</option>
<option value="OR">OR</option>
</select>

Thanks, this seems to work perfectly.

<select value="OH" id="selW9State" name="selW9State" required="">
<option value="">--</option>
<option value="NY">NY</option>
<option selected="selected" value="OH">OH</option>
<option value="OK">OK</option>

Yes, that’s what you should get with my latest code, but assuming, as I stated earlier, that the results variable is pointing to your <SELECT> element. My latest code loops through its children() (i.e. the <OPTION> elements) and sets the selected attribute on the proper one.

Thanks again. It looks great. I will have them put it through the paces.