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>
nameas selector, not sure why I would need to add classes