jquery获取和设置select单选和多选框带multiple属性的值

 剑鱼论坛 发表于 2020年06月27日 JS/jQuery  157
剑鱼论坛
LV 8 研究生
最后在线:2年前
加入时间:5年前
主帖:143  跟帖:100

我们在用jquery操作select下拉框的时候,一般情况下,如果select是单选的,那么我们会比较方便地使用如下代码来获取值:

$("#select option:selected").val();

我们还可以设置某个select选项被选中,即设置值:

$("#select option[value='v']").prop("selected",true);

但是当select是多选的情况,即select有multiple属性的情况下,我们使用以上方法会丢失部分值。

那么我们该怎么实现多选框的取值与赋值呢?

我们可以使用循环来实现取值和赋值,看下面的代码。

$("#select option:selected").each(function () {
console.log($(this).val());
});

上面这个代码就是循环取值的过程,执行后会在浏览器的控制台输出对应值。

我们再来看多选情况下的赋值代码:

$("#select option").each(function () {
$(this).prop("selected", true);
});

上面的代码就是多选框的赋值实现,这个代码会把多选框的所有选项都选中。

以上介绍了select选择框的单选和多选情况下的取值和赋值的jquery代码实现。上面的示例代码在实际编程中可以根据具体情况来使用和调整成符合实际需求的代码。

论坛主帖
288
论坛跟帖
316
在线访客
0
今日主帖
0
今日跟帖
0
今日注册
0
167
http://jianyuluntan.com/gentie.html
http://jianyuluntan.com/postzan.html
http://jianyuluntan.com/postcai.html
http://jianyuluntan.com/postshoucang.html
http://jianyuluntan.com/gentiezan.html
http://jianyuluntan.com/gentiecai.html
http://jianyuluntan.com/huifu.html
http://jianyuluntan.com/xiugai.html
http://jianyuluntan.com/shanchugentie.html
1
XzA=
1
© 2019 - 2024 剑鱼论坛 版权所有
Powered by JianYuLunTan
剑鱼论坛 976666861
http://jianyuluntan.com/feedback.html
http://jianyuluntan.com/qiandao.html
http://jianyuluntan.com/denglu.html
0
http://jianyuluntan.com/adenglu.html
0
剑鱼论坛