使用 jQuery 获取多个复选框的值并输出为逗号分隔的字符串. [英] Using jQuery to get multiple checkbox's value and output as comma separated String.
本文介绍了使用 jQuery 获取多个复选框的值并输出为逗号分隔的字符串.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多复选框,如下所示,
I have many checkboxs as below,
<li><input type="checkbox" name="areaofinterest" value="home_coo" id="home_coo" class="Checkbox" > Cooking</li>
<li><input type="checkbox" name="areaofinterest" value="home_cra" id="home_cra" class="Checkbox"> Crafts</li>
<li><input type="checkbox" name="areaofinterest" value="home_dec" id="home_dec" class="Checkbox"> Decorating</li>
<li><input type="checkbox" name="areaofinterest" value="home_ent" id="home_ent" class="Checkbox"> Entertaining</li>
<li><input type="checkbox" name="areaofinterest" value="home_gar" id="home_gar" class="Checkbox"> Gardening</li>
<li><input type="checkbox" name="areaofinterest" value="home_hom" id="home_hom" class="Checkbox"> Home Improvement</li>
<li><input type="checkbox" name="areaofinterest" value="home_mar" id="home_mar" class="Checkbox"> Marriage</li>
<li><input type="checkbox" name="areaofinterest" value="home_par" id="home_par" class="Checkbox"> Parenting</li>
<li><input type="checkbox" name="areaofinterest" value="home_pet" id="home_pet" class="Checkbox" > Pets</li>
<li><input type="checkbox" name="areaofinterest" value="home_ret" id="home_ret" class="Checkbox"> Retirement</li>
如何使用 jQuery 获取检查值并输出为 areaofinterest="home_coo,home_mar,home_pet" ?
How can I use jQuery to get the checked values and output as areaofinterest="home_coo,home_mar,home_pet" ?
非常感谢.
推荐答案
使用 .map()
函数:
Use the .map()
function:
$('.Checkbox:checked').map(function() {return this.value;}).get().join(',')
分解:
$('.Checkbox:checked')
选择选中的复选框.
.map(function() {return this.value;})
创建一个 jQuery 对象,该对象包含一个包含选中复选框值的数组.
.map(function() {return this.value;})
creates a jQuery object that holds an array containing the values of the checked checkboxes.
.get()
返回实际数组.
.join(',');
将数组的所有元素连接成一个字符串,用逗号分隔.
.join(',');
joins all of the elements of the array into a string, separated by a comma.
这篇关于使用 jQuery 获取多个复选框的值并输出为逗号分隔的字符串.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文