简体   繁体   中英

Selecting an option in a dropdown menu based on node value?

Is there a way to set the value of a dropdown list in jQuery (or Javascript) based on the node value?

 <select name="ddlProperty">
        <option value="1" selected="selected"></option>
        <option value="2">Animal Kingdom</option>
        <option value="3">Epcot</option>
        <option value="4">Hollywood Studios</option>
        <option value="5">Magic Kingdom</option>
        <option value="6">Downtown Disney</option>
</select>

I'd need to set the option of Magic Kingdom, so something like:

$("#ddlLocation").val("Magic Kingdom")

So that Magic Kingdom would become the selected item, that doesn't work as expected. Any ideas?

If you can use the value (not text!), do that using .val() :

$("#ddlProperty").val("5");

If you don't have that, use .filter() , .text() and .attr() to find and set the selected <option> , like this:

$("#ddlProperty option").filter(function() {
  return $(this).text() === "Magic Kingdom"
}).attr('selected', true);

Something like:

var box = document.getElementById('box'),
    options = box.options;

for(var i = 0; i < options.length; ++i){
    if(options[i].text == val){
        options[i].selected = true;
    }

}
$("#ddlProperty > option").each(function(i, elem) {
    if($(elem).text() == "Magic Kingdom") {
        $('#ddlProperty').val(elem.value);
        return false;
    }
});

And next time please make a proper example where the element has an id and that ID matches the ID in your code. I've spent about 5 minutes checking for an error until I've noticed the ID being different...

http://jsbin.com/ikibi3/2

myselect="Magic Kingdom";
$("select[name='ddlProperty'] option").each(function() {
    if($(this).text() == myselect) {
        $(this).attr('selected', true);
    } else {
        $(this).attr('selected', false);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM