使用jQuery获取多个checkbox的值并输出为逗号分隔的String。
我有很多复选框,如下所示,
Cooking Crafts Decorating Entertaining Gardening Home Improvement Marriage Parenting Pets Retirement
如何使用jQuery获取已检查的值并输出为areaofinterest =“home_coo,home_mar,home_pet”?
非常感谢。
使用.map()
函数:
$('.Checkbox:checked').map(function() {return this.value;}).get().join(',')
打破这种情况:
$('.Checkbox:checked')
选中已选中的复选框。
.map(function() {return this.value;})
创建一个jQuery对象,该对象包含一个包含已选中复选框值的数组。
.get()
返回实际的数组。
.join(',');
将数组的所有元素连接成一个字符串,用逗号分隔。
工作演示
var areaofinterest = ''; $('[name="areaofinterest"]').each(function(i,e) { var comma = areaofinterest.length===0?'':','; areaofinterest += (comma+e.value); });
仅获取复选框值:
var areaofinterest = ''; $('[name="areaofinterest"]').each(function(i,e) { if ($(e).is(':checked')) { var comma = areaofinterest.length===0?'':','; areaofinterest += (comma+e.value); } });
小提琴
你也可以这样做:
var areaofinterest = []; $('[name="areaofinterest"]:checked').each(function(i,e) { areaofinterest.push(e.value); }); areaofinterest = areaofinterest.join(',');
还有很多其他方法可以做到这一点?
var values = ""; $("checkbox[name=areaofinterest]").each(function() { values += $(this).val() + ","; }); values = values.substring(0, values.length - 2);
尝试这样的事情:
var areaofinterest= ""; $("input[type=\"checkbox\"]").each(function() { if ($(this).attr("checked")) { if (areaofinterest !== "") areaofinterest += ","; areaofinterest += $(this).value(); } });
或者你使用可以使用如下所示的数组
var checkBoxArray = new Array(); var areaofinterest = ''; $(':checkbox:checked').each(function(i){ checkBoxArray .push($(this).attr("value")); }); if (checkBoxArray .length == 0) { } else { while (checkBoxArray .length != 0) { if (checkBoxArray .length == 1) { areaofinterest += checkBoxArray .pop(); } else { areaofinterest += (checkBoxArray .pop() + ","); } } } console.log(areaofinterest);
虽然你会以相反的顺序得到String。