使用 jQuery 获取多个复选框的值并输出为逗号分隔的字符串。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11723297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:52:53  来源:igfitidea点击:

Using jQuery to get multiple checkbox's value and output as comma separated String.

jquerycheckbox

提问by Frank

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>

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

如何使用 jQuery 获取检查值并输出为 areaofinterest="home_coo,home_mar,home_pet" ?

Thanks a lot.

非常感谢。

回答by Anthony Grist

Use the .map()function:

使用.map()函数:

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

Breaking that down:

打破它:

$('.Checkbox:checked')selects the checked checkboxes.

$('.Checkbox:checked')选中选中的复选框。

.map(function() {return this.value;})creates a jQuery object that holds an array containing the values of the checked checkboxes.

.map(function() {return this.value;})创建一个 jQuery 对象,该对象包含一个包含选中复选框值的数组。

.get()returns the actual array.

.get()返回实际数组。

.join(',');joins all of the elements of the array into a string, separated by a comma.

.join(',');将数组的所有元素连接成一个字符串,用逗号分隔。

Working DEMO

工作演示

回答by adeneo

var areaofinterest = '';

$('[name="areaofinterest"]')?.each(function(i,e) {
    var comma = areaofinterest.length===0?'':',';
    areaofinterest += (comma+e.value);
})?;

To get only checked boxes value :

仅获取复选框值:

var areaofinterest = '';

$('[name="areaofinterest"]')?.each(function(i,e) {
    if ($(e).is(':checked')) {
        var comma = areaofinterest.length===0?'':',';
        areaofinterest += (comma+e.value);
    }
})?;

FIDDLE

小提琴

You could also do:

你也可以这样做:

var areaofinterest = [];
$('[name="areaofinterest"]:checked').each(function(i,e) {
    areaofinterest.push(e.value);
});

areaofinterest = areaofinterest.join(',');

And there's probably a bunch of other ways to do this ?

可能还有很多其他方法可以做到这一点?

回答by kush

 var mode = [];
            jQuery("input[name='mode[]']:checked").each(function(i) {
                mode.push($(this).val());
            });

回答by Anurag

Or you use can do using array like shown below

或者你可以使用如下所示的数组

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

though you will get String in reverse order.

虽然你会以相反的顺序得到 String 。

回答by Developer

Using jQuery to get multiple checkbox's value and output as comma separated String.

使用 jQuery 获取多个复选框的值并输出为逗号分隔的字符串。

var programming = $("input[name='programming']:checked").map(function() {
    return this.value;
}).get().join(', ');

alert("My favourite programming languages are: " + programming);

    OR

var favProgramming = [];
$.each($("input[name='programming']:checked"), function(){            
    favProgramming .push($(this).val());
});

alert("My favourite programming languages are: " + favProgramming);

FOR DEMO HERE

在这里进行演示

回答by Paul Aldred-Bann

Try something like this:

尝试这样的事情:

var areaofinterest= "";

$("input[type=\"checkbox\"]").each(function() {
    if ($(this).attr("checked")) {
        if (areaofinterest !== "") areaofinterest += ",";

        areaofinterest += $(this).value();
    }
});

回答by ?ukaszW.pl

var values = "";
$("checkbox[name=areaofinterest]").each(function() { 
    values += $(this).val() + ",";
});

values = values.substring(0, values.length - 2);