检查是否使用 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>