1

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!

1
  • 1
    Arrays are commonly used for storing data at integer indexes, not names like "group_one": in that case it makes more sense to use a plain object, not an array. Commented Jan 7, 2022 at 9:28

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.