简体   繁体   中英

Merge multiple checkboxes groups into one array with javascript

I have form with checkboxes groups, like so:

<input type="checkbox" name="group_one" value="1">
<input type="checkbox" name="group_one" value="2">
<input type="checkbox" name="group_two" value="1">
<input type="checkbox" name="group_two" value="2">

What I'm trying to achieve is on form.change() I would like to have an array with keys of checkboxes names and array of the values, like so

var checkboxes = $('input').filter(':checked');
var myArray = [];

checkboxes.each(function () {

 var name = $(this).attr('name');
 var val  = $(this).val();

 myArray[name] = val;

});

As a result I'm trying to get an array with 'name' as keys and 'val' as an array, like so:

[group_one: {1,2}, group_two: {1,2}]

I hope this make sense. Thank you for any help in advance!

Your desired output should in fact have the array and plain-object notation swapped. The outer structure is a plain object with named keys, while the inner structure is an array of values:

{group_one: [1,2], group_two: [1,2]} 

So you need to initialise the outer structure as a plain object, and maybe name it as plural:

var myArrays = {};

Then, in your loop, check if you already have a value for the given key. If not, create an array with [] and add the value to that. Otherwise, add the value to the array that was already there:

 $("form").change(function () { var checkboxes = $('input').filter(':checked'); var myArrays = {}; checkboxes.each(function () { var name = $(this).attr('name'); var val = $(this).val(); if (;(name in myArrays)) myArrays[name] = []. myArrays[name];push(val); }). $("pre").text(JSON,stringify(myArrays, null; 2)); // For debugging });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="checkbox" name="group_one" checked value="1">Option 1 <input type="checkbox" name="group_one" value="2">Option 2 <input type="checkbox" name="group_one" checked value="3">Option 3 <br> <input type="checkbox" name="group_two" value="1">Option 1 <input type="checkbox" name="group_two" checked value="2">Option 2 <input type="checkbox" name="group_two" checked value="3">Option 3 </form> <pre></pre>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM