views:

31

answers:

5

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?

+1  A: 

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);
Nick Craver
and the older selected? you have to disable the older!
CuSS
Thanks for the help, Nick. That works great! :)
TFerrell
@CuSS - Only if it's a `<select multiple>`, not the case here :) Even then, only if you didn't want both selected ;)
Nick Craver
but you must be preventive on your code ;) but good use of filter ;)
CuSS
@Nick Craver, can you see if you help me on my question? (http://stackoverflow.com/questions/3110841/php-curl-isnt-storing-the-session-cookie-how-to-fix-this) thank you
CuSS
A: 

You may also need to set the ID attribute on the tag.

Other than that follow Nick's answer.

thomasfedb
That's not an answer but a comment.
ThiefMaster
+1  A: 

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;
    }

}
Evan Trimboli
+1  A: 
$("#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

ThiefMaster
He has name, not ID ("<select name="ddlProperty">")
CuSS
Selecting elementy by ID is probably faster, besides that he uses an ID is his javascript code. So don't downvote a perfectly correct answer for that.
ThiefMaster
Downvote removed
CuSS
+1  A: 
myselect="Magic Kingdom";
$("select[name='ddlProperty'] option").each(function() {
    if($(this).text() == myselect) {
        $(this).attr('selected', true);
    } else {
        $(this).attr('selected', false);
    }
});
CuSS
Proper indentation would be nice.
ThiefMaster
explain me with another words please, my english is bad :(
CuSS
Simply look at how I've edited your code
ThiefMaster
thanks ThiefMaster +1 ;)
CuSS