Javascript 使用 jQuery 获取选定复选框的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11292778/
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-24 05:19:40  来源:igfitidea点击:

use jQuery to get values of selected checkboxes

javascriptjquery

提问by Flo

I want to loop through the checkboxgroup 'locationthemes' and build a string with all selected values. So when checkbox 2 and 4 are selected the result would be: "3,8"

我想遍历复选框组“locationthemes”并构建一个包含所有选定值的字符串。So when checkbox 2 and 4 are selected the result would be: "3,8"

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>
<input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>

I checked here: http://api.jquery.com/checked-selector/but there's no example how to select a checkboxgroup by its name.

我在这里检查:http: //api.jquery.com/checked-selector/但没有示例如何按名称选择复选框组。

How can I do this?

我怎样才能做到这一点?

回答by Fabrizio Calderan

In jQuery just use an attribute selector like

在 jQuery 中,只需使用一个属性选择器,如

$('input[name="locationthemes"]:checked');

to select all checked inputs with name "locationthemes"

选择名称为“locationthemes”的所有选中的输入

console.log($('input[name="locationthemes"]:checked').serialize());

//or

$('input[name="locationthemes"]:checked').each(function() {
   console.log(this.value);
});

Demo

演示



In VanillaJS

VanillaJS 中

[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
   console.log(cb.value); 
});

Demo

演示



In ES6/spread operator

在 ES6/spread 运算符中

[...document.querySelectorAll('input[name="locationthemes"]:checked')]
   .forEach((cb) => console.log(cb.value));

Demo

演示

回答by Talha

$('input:checkbox[name=locationthemes]:checked').each(function() 
{
   // add $(this).val() to your array
});

Working Demo

工作演示

OR

或者

Use jQuery's is()function:

使用jQuery的is()功能:

$('input:checkbox[name=locationthemes]').each(function() 
{    
    if($(this).is(':checked'))
      alert($(this).val());
});

?

?

回答by Steffan Perry

Map the array is the quickest and cleanest.

映射数组是最快和最干净的。

var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })

will return values as an array like:

将作为数组返回值,如:

array => [2,3]

assuming castle and barn were checked and the others were not.

假设城堡和谷仓被检查,其他人没有。

回答by usr4217

$("#locationthemes").prop("checked")

$("#locationthemes").prop("checked")

回答by MaylorTaylor

Using jquery's mapfunction

使用jquery的map功能

var checkboxValues = [];
$('input[name=checkboxName]:checked').map(function() {
            checkboxValues.push($(this).val());
});

回答by Tushar Sagar

You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();

回答by mike

So all in one line:

所以在一行中:

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");

..a note about the selector [id*="checkbox"], it will grab any item with the string "checkbox" in it. A bit clumsy here, but really good if you are trying to pull the selected values out of something like a .NET CheckBoxList. In that case "checkbox" would be the name that you gave the CheckBoxList control.

..关于选择器的说明[id*="checkbox"],它将抓取任何包含字符串“checkbox”的项目。这里有点笨拙,但如果您试图从 .NET CheckBoxList 之类的东西中提取选定的值,那真的很好。在这种情况下,“checkbox”将是您为 CheckBoxList 控件提供的名称。

回答by Anmol Mourya

var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      

回答by thecodedeveloper.com

Source - More Detail

来源 - 更多细节

Get Selected Checkboxes Value Using jQuery

使用 jQuery 获取选中的复选框值

Then we write jQuery script to get selected checkbox value in an array using jQuery each(). Using this jQuery function it runs a loop to get the checked value and put it into an array.

然后我们编写 jQuery 脚本来使用 jQuery each() 获取数组中选中的复选框值。使用这个 jQuery 函数,它运行一个循环来获取检查的值并将其放入一个数组中。

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Get Selected Checkboxes Value Using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".btn").click(function() {
                var locationthemes = [];
                $.each($("input[name='locationthemes']:checked"), function() {
                    locationthemes.push($(this).val());
                });
                alert("My location themes colors are: " + locationthemes.join(", "));
            });
        });
    </script>
    </head>
    <body>
        <form method="POST">
        <h3>Select your location themes:</h3>
        <input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
        <label for="checkbox-1">Castle</label>
        <input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
        <label for="checkbox-2">Barn</label>
        <input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
        <label for="checkbox-3">Restaurant</label>
        <input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
        <label for="checkbox-4">Bar</label>
        <br>
        <button type="button" class="btn">Get Values</button>
    </form>
    </body>
    </html>

回答by Khurram Shaukat

var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
     SlectedList.push($(this).val());
});