How to change the selected index when I only have a name?

I integrate the zip code anywhere with my web project. I am using drop drop for the county / state field. A zip code anywhere returns the name of the county. Can I change the selected index when I only have a name? (I use a number for the value field related to the database field).

I tried the following:

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

I tried to include the html dropdown code here, but for some reason I can't get it to work fine.

But of course, this just changes the text box for the item in the drop-down list that is already selected.

I can query the database and find out which identifier I assigned to the county, but I would prefer if there is another way.

+3
source share
3

, :

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

.

+2

:

: 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");
+2

Just an option for 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>
+1
source

All Articles