jq如何获取选中option的值_使用jquery操作select(获取选中option的值等)

$('#ITEM_CODE option:selected').text()获取被选中的文本值。不是value值

总结下使用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)。

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>