jQuery jQuery获取选中复选框的值到数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16170828/
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
jQuery get values of checked checkboxes into array
提问by if __name__ is None
I am trying to get values of all checkboxes that are currently checked and store them into an array. Here is my code so far:
我试图获取当前选中的所有复选框的值并将它们存储到一个数组中。到目前为止,这是我的代码:
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
});
console.log(searchIDs);
});
However this outputs more than I need. I not only get the values, but some other stuff I don't want.
然而,这输出的比我需要的多。我不仅获得了值,还获得了一些我不想要的其他东西。
["51729b62c9f2673e4c000004", "517299e7c9f26782a7000003", "51729975c9f267f3b5000002", prevObject: jQuery.fn.jQuery.init[3], context: document, jquery: "1.9.1", constructor: function, init: function…]
["51729b62c9f2673e4c000004", "517299e7c9f26782a7000003", "51729975c9f267f3b5000002", prevObject: "jQuery.fn.query.init,...
I would like just ID's (first 3 items in this case).
我只想要 ID(在这种情况下是前 3 个项目)。
By using $.each
and pushing values to an array I get desired output:
通过使用$.each
并将值推送到数组,我得到了所需的输出:
$("#find-table input:checkbox:checked").each(function(){ myArray.push($(this).val()); })
["51729b62c9f2673e4c000004", "517299e7c9f26782a7000003", "51729975c9f267f3b5000002"]
[“51729b62c9f2673e4c000004”、“517299e7c9f26782a7000003”、“51729975c9f267f3b5000002”]
However I'd like to use $.map
, since it saves me a line of code and is prettier.
但是我想使用$.map
,因为它为我节省了一行代码并且更漂亮。
Thanks
谢谢
回答by Andrew Whitaker
Call .get()
at the very end to turn the resulting jQuery object into a true array.
.get()
在最后调用将生成的 jQuery 对象转换为真正的数组。
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
console.log(searchIDs);
});
Per the documentation:
根据文档:
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.
由于返回值是一个包含数组的 jQuery 对象,因此在结果上调用 .get() 以使用基本数组是很常见的。
回答by Cristi Pufu
DEMO: http://jsfiddle.net/PBhHK/
演示:http: //jsfiddle.net/PBhHK/
$(document).ready(function(){
var searchIDs = $('input:checked').map(function(){
return $(this).val();
});
console.log(searchIDs.get());
});
Just call get() and you'll have your array as it is written in the specs: http://api.jquery.com/map/
只需调用 get() ,您就会拥有规范中编写的数组:http: //api.jquery.com/map/
$(':checkbox').map(function() {
return this.id;
}).get().join();
回答by tymeJV
You need to add .toArray()
to the end of your .map()
function
您需要添加.toArray()
到.map()
函数的末尾
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
}).toArray();
console.log(searchIDs);
});
回答by Mark Meyer
I refactored your code a bit and believe I came with the solution for which you were looking. Basically instead of setting searchIDs
to be the result of the .map()
I just pushed the values into an array.
我稍微重构了您的代码,并相信我提供了您正在寻找的解决方案。基本上searchIDs
,.map()
我只是将值推入数组,而不是设置为结果。
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = [];
$("#find-table input:checkbox:checked").map(function(){
searchIDs.push($(this).val());
});
console.log(searchIDs);
});
I created a fiddlewith the code running.
我创建了一个运行代码的小提琴。
回答by Thalinda Bandara
var ids = [];
$('input[id="find-table"]:checked').each(function() {
ids.push(this.value);
});
This one worked for me!
这个对我有用!
回答by Qammar Feroz
var idsArr = [];
$('#tableID').find('input[type=checkbox]:checked').each(function() {
idsArr .push(this.value);
});
console.log(idsArr);
回答by i_a
Needed the form elements named in the HTML as an array to be an array in the javascript object, as if the form was actually submitted.
需要将 HTML 中命名的表单元素作为数组作为 javascript 对象中的数组,就好像表单是实际提交的一样。
If there is a form with multiple checkboxes such as:
如果有一个带有多个复选框的表单,例如:
<input name='breath[0]' type='checkbox' value='presence0'/>
<input name='breath[1]' type='checkbox' value='presence1'/>
<input name='breath[2]' type='checkbox' value='presence2'/>
<input name='serenity' type='text' value='Is within the breath.'/>
...
The result is an object with:
结果是一个对象:
data = {
'breath':['presence0','presence1','presence2'],
'serenity':'Is within the breath.'
}
var $form = $(this),
data = {};
$form.find("input").map(function()
{
var $el = $(this),
name = $el.attr("name");
if (/radio|checkbox/i.test($el.attr('type')) && !$el.prop('checked'))return;
if(name.indexOf('[') > -1)
{
var name_ar = name.split(']').join('').split('['),
name = name_ar[0],
index = name_ar[1];
data[name] = data[name] || [];
data[name][index] = $el.val();
}
else data[name] = $el.val();
});
And there are tons of answers here which helped improve my code, but they were either too complex or didn't do exactly want I wanted: Convert form data to JavaScript object with jQuery
这里有大量的答案有助于改进我的代码,但它们要么太复杂,要么不是我想要的:Convert form data to JavaScript object with jQuery
Works but can be improved: only works on one-dimensional arrays and the resulting indexes may not be sequential. The length property of an array returns the next index number as the length of the array, not the actually length.
有效但可以改进:仅适用于一维数组,结果索引可能不是顺序的。数组的长度属性返回下一个索引号作为数组的长度,而不是实际长度。
Hope this helped. Namaste!
希望这有帮助。合十礼!
回答by Manish
here allows is class of checkboxes on pages and var allows collects them in an array and you can check for checked true in for loop then perform the desired operation individually. Here I have set custom validity. I think it will solve your problem.
这里允许是页面上的复选框类,var 允许将它们收集在一个数组中,您可以检查 for 循环中的检查是否为真,然后单独执行所需的操作。这里我设置了自定义有效期。我认为它会解决你的问题。
$(".allows").click(function(){
var allows = document.getElementsByClassName('allows');
var chkd = 0;
for(var i=0;i<allows.length;i++)
{
if(allows[i].checked===true)
{
chkd = 1;
}else
{
}
}
if(chkd===0)
{
$(".allows").prop("required",true);
for(var i=0;i<allows.length;i++)
{
allows[i].setCustomValidity("Please select atleast one option");
}
}else
{
$(".allows").prop("required",false);
for(var i=0;i<allows.length;i++)
{
allows[i].setCustomValidity("");
}
}
});
回答by MItrajyoti Kusari
Do not use "each". It is used for operations and changes in the same element. Use "map" to extract data from the element body and using it somewhere else.
不要使用“每个”。它用于同一元素中的操作和更改。使用“map”从元素主体中提取数据并在其他地方使用它。