Fil Fil - 5 months ago 12
Javascript Question

How to get the value of the checked boxes in jquery

I have a following code in html, which use checkbox align as a row

<tr class="reg_name">
<th class="custom-th">Reg. Name</th>
<td class="text-center"><input type="checkbox" name="reg_name[]" value="Y:1"></td>
<td class="text-center"><input type="checkbox" name="reg_name[]" value="N:1"></td>
<td class="text-center"><input type="checkbox" name="reg_name[]" value="B:1"></td>
<td class="text-center"><input type="checkbox" name="reg_name[]" value="I:1"></td>
</tr>


with a button

<button type="button" class="purchase__save btn btn-default pull-right">Save</button>


and this js code,

$(document).ready(function() {
$('.purchase__save').click(function() {
var box_array = [];
var boxes = $('.reg_name input[name="reg_name[]"]:checked');
for (var i = 0; i < boxes.length; i++) {
box_array[i] = boxes.val();
}
console.log(box_array);
});
});


will try to get the value of checked box.

The problem, if try to check two checkboxes at the same time, the value from
this
<td class="text-center"><input type="checkbox" name="reg_name[0]" value="Y:1"></td>
is the only thing I get.

How to get values of other checkboxes if they are checked?

Answer

$(document).ready(function() {
  $('.purchase__save').click(function() {
    var box_array = [];
    var boxes = $('input:checkbox:checked');
    $.each(boxes, function(i,v) {
      box_array[i] = $(this).val();


    })

    console.log(box_array);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="reg_name">
    <td class="text-center">
      <input type="checkbox" name="reg_name" value="Y:1">
    </td>
    <td class="text-center">
      <input type="checkbox" name="reg_name" value="N:1">
    </td>
    <td class="text-center">
      <input type="checkbox" name="reg_name" value="B:1">
    </td>
    <td class="text-center">
      <input type="checkbox" name="reg_name" value="I:1">
    </td>
  </tr>
</table>

<button type="button" class="purchase__save btn btn-default pull-right">Save</button>

  1. Use $(this) to get current checkbox value