I am trying to get an array of selected checkboxes values and text on button click
<input type="checkbox" name="checkbox[]" value="1" /><label>text1</label>
<input type="checkbox" name="checkbox[]" value="2" /><label>text2</label>
<input type="checkbox" name="checkbox[]" value="3" /><label>text3</label>
<input type="checkbox" name="checkbox[]" value="4" /><label>text4</label>
I'm getting values of the checkboxes but how to get text also in array
var checkboxes = document.getElementsByName('checkbox[]');
var vals = 0;
for (var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked) {
vals += ","+checkboxes[i].value;
}
}
Thank you!
You can use map()
to create an array of the values you require:
var labelValues = $(':checkbox:checked').map(function() {
return [ $(this).next('label').text(), this.value ];
}).get();
However given your desired output it would make more sense to create an object with the labels as the properties, something like this:
var obj = {};
$(':checkbox:checked').each(function() {
obj[$(this).next('label').text()] = this.value;
});
-- 2021 Update --
You can now simplify the map()
call using an ES6 arrow function. In addition you could combine the checkbox value and label text in to an array of objects, like this:
$(':checkbox').on('change', () => {
let labelValues = $(':checkbox:checked').map((i, el) => ({
value: el.value,
text: el.nextElementSibling.textContent
})).get();
console.log(labelValues);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox[]" value="1" /><label>text1</label>
<input type="checkbox" name="checkbox[]" value="2" /><label>text2</label>
<input type="checkbox" name="checkbox[]" value="3" /><label>text3</label>
<input type="checkbox" name="checkbox[]" value="4" /><label>text4</label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With