首页 > 解决方案 > 使用 jQuery 在选择列表中设置默认值

问题描述

如果我的下拉列表中只有一个选项,我需要选择此选项作为默认选项。如何使用 jQuery 做到这一点?

标签: javascriptjqueryformsselect

解决方案


我认为您是 SO 新手,这里的通常程序是在发布之前提供一些您自己在此问题上的努力的代码。也就是说,这是简单的 JQuery:

编辑以适应新规范:

if($("#select_id option").length == 2){ //if there are exactly 2 options in the select element
    $("#select_id option:nth(1)").attr("selected",true); //take the second option (element 0) inside the element with id "select_id" and set the selected attribute.
} //I think we do not need an else if any other thing will select the first option by default

无论如何,默认情况下应选择第一个选项。

<select id="select_id">
    <option value=1>First option is selected by default</option>
</select>
<!--adding proof that it is selected-->
<script>
    $(function(){
         alert($("#select_id").val()); //this will alert 1, since is the value of my first option
    });
</script>

推荐阅读