开发者

jQuery select dropdown and selectedq

   var colorID = 3;
   $('#color').each(function(){
   if($('#color').val() == colorID )
      $('#color').attr('selected');
 开发者_Go百科  });

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>


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.


Try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜