tags:

views:

30

answers:

2

Hi,

   var colorID = 3;
   $('#color').each(function(){
   if($('#color').val() == colorID )
      $('#color').attr('selected');
   });

Why doesn't this work?

My html

<select id="color"><option value="">Select Color</option>
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Black</option>
<option value="4">Purple</option>
</select>
+4  A: 

You can just use .val() to get/set the value of any input style element, including a <select>:

$('#color').val(3);

You can test it out here. For illustration here's a working long-hand version of what you were attempting:

var colorID = 3;
$('#color option').each(function(){
if ($(this).val() == colorID)
  $(this).attr('selected', true);
});

You were looping through but then checking the <select>, not the <option> elements, which doesn't have those properties.

Nick Craver
Wasn't it `selected="selected"` instead of true? true works in upto 2 browsers as far as I remember.
naugtur
@naugtur - DOM != markup, it's a boolean property :) The reason `"selected"` works is that any non-empty string is "true" as well. Also in markup it's *supposed* to be just `selected`, no equals or value :) The above will work for all browsers :)
Nick Craver
@Nick - I can't remember, but I had some problems with that once. In an old browser.
naugtur
@naugtur - do remember that jQuery normalizes some things under the hood as well. When you *get* this attribute, for example: `.attr("selected")` you'll get a boolean `true`/`false` coming out as well :)
Nick Craver
@Nick - that's right. That memory of mine was from 3 years before. Sorry for making a fuss ;)
naugtur
A: 

Try this:

   var colorID = '3';
   $('#color option').each(function(){
        if($(this).val() == colorID)
        {
            $(this).attr('selected', 'selected');
        }
   });
Otar
Cool, but `$(this).attr('selected');` is a getter, and that's the problem.
naugtur
You are right, I copy/pasted the code without noticing it...
Otar