检查是否使用jQuery选择了选项,如果没有选择默认选项

问题描述:

使用jQuery,如何检查选择菜单中是否选择了一个选项,如果没有,可以选择一个选项。

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.

选择是在我刚刚继承的应用程序中产生一个迷宫的PHP函数,所以这是一个快速的修复,而我的头脑围绕着这些:)

(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 :)

虽然我不确定你想要完成什么,但这段代码对我有用。

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>