Sushant Sushant -4 years ago 112
Javascript Question

Get value and text of selected checkboxes

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!

Answer Source

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 ];

Working example

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;

Working example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download