javascript - 使用 jQuery 在选择列表中设置默认值
问题描述
如果我的下拉列表中只有一个选项,我需要选择此选项作为默认选项。如何使用 jQuery 做到这一点?
解决方案
我认为您是 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>
推荐阅读
- javascript - 使用 google 表格作为数据库从代码进行身份验证
- pdf - PDF 隐藏对象
- reactjs - 我们什么时候应该在 React 类中定义一个函数作为箭头函数?
- javascript - 为什么我不能在 .querySelector 函数的选择器中使用变量?
- android - 将多个微调器相互链接,并使每个项目只能选择一次
- r - 在 Plumber API R 中获取 CSV 作为输入和输出 CSV
- jquery - 如何使用jQuery在关联数组中获取表单的输入值
- dependency-injection - 如何解决错误:[Dagger/MissingBinding] 在使用带有 Dagger2 的 Retrofit 时
- bluetooth-lowenergy - 如何构建一个充当外围蓝牙的 android 应用程序,以便我可以从 iOS 应用程序中发现它?
- elastic-stack - Kibana apm 仪表板错误:响应中缺少聚合键,请检查您对此请求的权限