js获取选中的文字(jq如何获取选中option的值_使用jquery操作select(获取选中option的值等))
总结下使用jQuery操作select的方法 。
1.获取第一个候选项的值 。
$(#test option:first).val();
2.获取最后一个候选项的值 。
$(#test option:last).val();
3.获取第二个候选项的值 。
$(#test option:eq(1)).val();
4.获取选中的候选项的值 。
$(#test).val();
$(#test option:selected).val();
5.设置值为2的候选项为选中状态 。
$(#test).attr(value,2);
6.设置最后一个候选项为选中 。
$(#test option:last).attr(selected,selected);
$("#test").attr(value , $(#test option:last).val());
$("#test").attr(value , $(#test option).eq($(#test option).length - 1).val());
7.获取候选项列表的长度 。
$(#test option).length;
8.添加一个候选项 。
$("#test").append("第N+1项");
$("第N+1项").appendTo("#test");
9.删除选中项 。
$(#test option:selected).remove();
10.删除项(这里删除第一项) 。
$(#test option:first).remove();
11.删除指定值。
$(#test option).each(function() {if ($(this).val() == 5){
$(this).remove();
}
});
$(#test option[value=5]).remove();
12.获取第一个分组的标签 。
$(#test optgroup:eq(0)).attr(label);
13.获取第二个分组下面第一个候选项的值 。
$(#test optgroup:eq(1) : option:eq(0)).val();
14.根据候选项的值选中候选项。
$("#sel option:contains(C)").prop("selected", true);
select在业务表单中使用得非常多 ,掌握如何使用jQuery去操作select是很有必要的 ,即使现在的前端发展趋势是提倡操作数据而避免直接操作dom(比如vue) 。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!