flyersun
flyersun

Reputation: 917

How to change Selected Index when I only have the name?

I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).

I tried the following:

var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;

I've tried to include the drop down code html here but I can't get it to work properly for some reason.

But of course this just changes the text field for the item in the drop down that is already selected.

I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.

Upvotes: 3

Views: 6819

Answers (3)

RobG
RobG

Reputation: 147413

Just a variation on other answers:

<script type="text/javascript">

function setValue(el, value) {
  var sel = el.form.sel0;
  var i = sel.options.length;
  while (i--) {
    sel.options[i].selected = sel.options[i].text == value;
  }
}

</script>
<form>
<select name="sel0">
  <option value="0" selected>China
  <option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>

Upvotes: 1

Neysor
Neysor

Reputation: 3909

I would make a function and loop over the labels:

See: http://jsfiddle.net/Y3kYH/

<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>​

JavaScript

function selectElementByName(id, name) {
    f = document.getElementById(id);
    for(i=0;i<f.options.length;i++){
        if(f.options[i].label == name){
            f.options.selectedIndex = i;
            break;
        }
    }
}
selectElementByName("country","B");

Upvotes: 2

karim79
karim79

Reputation: 342655

Loop over the options until you have a match:

for (var i = 0; i < f.options.length; i++) {
    if (f.options[i].text == response[0].Country) {
        f.options.selectedIndex = i;
        break;
    }
}

Demo.

Upvotes: 2

Related Questions