0

I have several groups of checkboxes in a form. For each grouping of checkboxes(by name) I want to create an array and if the box is checked, add it to that particular array and if it's unchecked, remove it. I have that working like this:

var color = [];
var size = [];
$('input[name="color[]"]').change(function () {
  color = $('input[name="color[]"]:checked').map(function(i) {
    return $(this).val();
  }).get();
  console.log(color);
});

$('input[name="size[]"]').change(function () {
  size = $('input[name="size[]"]:checked').map(function(i) {
    return $(this).val();
  }).get();
  console.log(size);
});
label {
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <h4>Color</h4>
  <label>
    <input type="checkbox" name="color[]" value="red" />
    Red
  </label>
  <label>
    <input type="checkbox" name="color[]" value="green" />
    Green
  </label>
  <label>
    <input type="checkbox" name="color[]" value="blue" />
    Blue
  </label>
  <h4>Size</h4>
  <label>
    <input type="checkbox" name="size[]" value="small" />
    Small
  </label>
  <label>
    <input type="checkbox" name="size[]" value="medium" />
    Medium
  </label>
  <label>
    <input type="checkbox" name="size[]" value="large" />
    Large
  </label>
</form>

What I'm wondering is if there's a way to do this dynamically so that instead of having a separate change function for each grouping of checkboxes(there will be many) is there a way to combine this into one change function and have it map to the correct array based on the name? Something like this:

var color = [];
var size = [];
$('input[type="checkbox"]').change(function () {
  var group = $(this).attr('name');
  value = $('input[name="' + group + '"]:checked').map(function(i) {
    return $(this).val();
  }).get();
  console.log(color);
  console.log(size);
});
label {
  display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <h4>Color</h4>
  <label>
    <input type="checkbox" name="color[]" value="red" />
    Red
  </label>
  <label>
    <input type="checkbox" name="color[]" value="green" />
    Green
  </label>
  <label>
    <input type="checkbox" name="color[]" value="blue" />
    Blue
  </label>
  <h4>Size</h4>
  <label>
    <input type="checkbox" name="size[]" value="small" />
    Small
  </label>
  <label>
    <input type="checkbox" name="size[]" value="medium" />
    Medium
  </label>
  <label>
    <input type="checkbox" name="size[]" value="large" />
    Large
  </label>
</form>

2
  • Use html classes to grab checkbox inputs you want select together. Then add those classes to your selector Commented Jan 31, 2020 at 16:15
  • I am already using name as selector, not sure why I would need to add classes Commented Jan 31, 2020 at 16:21

1 Answer 1

1

I believe this is what you want. I've set up a codepen to demonstrate.

Tip here: Any time you want to initialise an arbitrary number of variables that you can access later in the global scope, it's usually a good idea to initialise them as properties on an object in the global scope.

const groups = {};

$('input[type="checkbox"]').on("change", function (e) {
  const checkedInput = $(e.target);
  const groupName = checkedInput.attr('name');

  const updatedArray = $(`input[name="${groupName}"]:checked`).map(function(i) {
        return $(this).val();
      }).get();

  groups[groupName] = updatedArray;

  console.log(groups[groupName]);
});
Sign up to request clarification or add additional context in comments.

3 Comments

This does seem to be close to what I'm looking for, but I'm not clear on how to differentiate between the various arrays that are created. I see that I am getting separate arrays that are populated with the checked inputs for their associated group, but how do I know which array is the color array and which is the size array? My thought was that I would declare an array for each group of options and then push the checked values to the associated array.
@user13286 Good to hear it! One suggestion, though: a good practice on StackOverflow and other Q&A boards is to never post a comment like your second comment: "Never mind, I figured it out!". If you can instead explain what solution you found, there are two benefits: 1) You'll have the benefit of understanding it more thoroughly because you explained it in writing. 2) Anybody who has this problem will benefit from reading your solution. You can probably imagine the agony of finding somebody who has the same problem as you and solved it, but didn't bother sharing what they did.
In this case I'll post it for anybody reading: the arrays can be retrieved afterwards from the Object on which we created the properties. The property name will be the same as the groupName variable. In this case, if we want the color array, we'll look at groups['color'].

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.