Check if option is selected with jQuery, if not se

2019-01-03 07:33发布

Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.

(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)

18条回答
闹够了就滚
2楼-- · 2019-01-03 08:26

While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.

<select id="mySelect" multiple="multiple">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length) {
    $("#mySelect option[value='3']").attr('selected', 'selected');
  }
});
</script>
查看更多
爷的心禁止访问
3楼-- · 2019-01-03 08:27

No need to use jQuery for this:

var foo = document.getElementById('yourSelect');
if (foo)
{
   if (foo.selectedIndex != null)
   {
       foo.selectedIndex = 0;
   } 
}
查看更多
爷的心禁止访问
4楼-- · 2019-01-03 08:28

Easy! The default should be the first option. Done! That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :)

Unobtrusive JavaScript

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-03 08:28
$("#select_box_id").children()[1].selected

This is another way of checking an option is selected or not in jquery. This will return Boolean (True or False).

[1] is index of select box option

查看更多
我命由我不由天
6楼-- · 2019-01-03 08:30

Look at the selectedIndex of the select element. BTW, that's a plain ol' DOM thing, not JQuery-specific.

查看更多
倾城 Initia
7楼-- · 2019-01-03 08:31
$("option[value*='2']").attr('selected', 'selected');
// 2 for example, add * for every option
查看更多
登录 后发表回答