使用jQuery获取多个复选框的值并输出为逗号分隔的字符串。 [英] Using jQuery to get multiple checkbox's value and output as comma separated String.

查看:127
本文介绍了使用jQuery获取多个复选框的值并输出为逗号分隔的字符串。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多复选框如下:

<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>



How can I use jQuery to get the checked values and output as areaofinterest="home_coo,home_mar,home_pet" ?

非常感谢。

推荐答案

http://api.jquery.com/map/> .map() 功能:

Use the .map() function:

$('.Checkbox:checked').map(function() {return this.value;}).get().join(',')

折断:

$('。Checkbox:checked')选择复选框。

.map 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.

工作DEMO

这篇关于使用jQuery获取多个复选框的值并输出为逗号分隔的字符串。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆