jQuery将复选框的值获取到数组中

时间:2022-11-30 11:18:53

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.jQuery。init[3], context: document, jquery: "1.9.1",构造函数:function, init: function…

I would like just ID's (first 3 items in this case).

我只需要ID(这里的前三项)。

By using $.each and pushing values to an array I get desired output:

通过使用美元。把每个值推到一个数组中,我得到了想要的输出:

$("#find-table input:checkbox:checked").each(function(){ myArray.push($(this).val()); })

["51729b62c9f2673e4c000004", "517299e7c9f26782a7000003", "51729975c9f267f3b5000002"]

[" 51729 b62c9f2673e4c000004”、“517299 e7c9f26782a7000003”,“51729975 c9f267f3b5000002”)

However I'd like to use $.map, since it saves me a line of code and is prettier.

但是我想用$。map,因为它节省了一行代码,而且更漂亮。

Thanks

谢谢

9 个解决方案

#1


209  

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()来处理基本数组是非常常见的。

#2


19  

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(),您就会得到在spec中写入的数组:http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

#3


15  

You need to add .toArray() to the end of your .map() function

您需要在.map()函数的末尾添加.toArray()

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();
    }).toArray();
    console.log(searchIDs);
});

Demo: http://jsfiddle.net/sZQtL/

演示:http://jsfiddle.net/sZQtL/

#4


9  

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 fiddle with the code running.

我创建了一个运行代码的小提琴。

#5


3  

     var ids = [];

$('input[id="find-table"]:checked').each(function() {
   ids.push(this.value); 
});

This one worked for me!

这个对我起作用了!

#6


0  

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”从元素主体中提取数据并在其他地方使用它。

#7


0  

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

这里有大量的答案可以帮助改进我的代码,但它们要么太复杂,要么不是我想要的:用jQuery将表单数据转换为JavaScript对象

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.

可以工作,但可以改进:只能在一维数组中工作,结果索引可能不是顺序的。数组的length属性返回下一个索引号作为数组的长度,而不是实际的长度。

Hope this helped. Namaste!

希望这个有帮助。合十礼!

#8


0  

var idsArr = [];

$('#tableID').find('input[type=checkbox]:checked').each(function() {
    idsArr .push(this.value);
});

console.log(idsArr);

#9


0  

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循环中选中true,然后分别执行所需的操作。这里我设置了自定义有效性。我认为这将解决你的问题。

  $(".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("");
        }
   }

}); 

#1


209  

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()来处理基本数组是非常常见的。

#2


19  

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(),您就会得到在spec中写入的数组:http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

#3


15  

You need to add .toArray() to the end of your .map() function

您需要在.map()函数的末尾添加.toArray()

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();
    }).toArray();
    console.log(searchIDs);
});

Demo: http://jsfiddle.net/sZQtL/

演示:http://jsfiddle.net/sZQtL/

#4


9  

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 fiddle with the code running.

我创建了一个运行代码的小提琴。

#5


3  

     var ids = [];

$('input[id="find-table"]:checked').each(function() {
   ids.push(this.value); 
});

This one worked for me!

这个对我起作用了!

#6


0  

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”从元素主体中提取数据并在其他地方使用它。

#7


0  

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

这里有大量的答案可以帮助改进我的代码,但它们要么太复杂,要么不是我想要的:用jQuery将表单数据转换为JavaScript对象

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.

可以工作,但可以改进:只能在一维数组中工作,结果索引可能不是顺序的。数组的length属性返回下一个索引号作为数组的长度,而不是实际的长度。

Hope this helped. Namaste!

希望这个有帮助。合十礼!

#8


0  

var idsArr = [];

$('#tableID').find('input[type=checkbox]:checked').each(function() {
    idsArr .push(this.value);
});

console.log(idsArr);

#9


0  

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循环中选中true,然后分别执行所需的操作。这里我设置了自定义有效性。我认为这将解决你的问题。

  $(".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("");
        }
   }

});