Home > Net >  jquery returns last changed checkbox on bulk check/uncheck
jquery returns last changed checkbox on bulk check/uncheck

Time:02-18

I am trying to get data-region-code attribute from all the checkbox that were changed (checked/unchecked). But with my code, I am getting the last changed checkbox, not all the checkboxes. For eg: If I'm changing checkbox for data-region-code 001, 002, 003, 004, I will get the value as 004 as it is the last changed checkbox.
For reference: when checkbox is changed, I add class=changed for input.

Structure (I have more tr, maybe around 18-20 with same structure):

<table class= settings-container">
  <thead></thead>
  <tbody>
    <tr id="">
      <td></td>
      <td></td>
      <td>
         <input type="checkbox" name="blockage_simulation[]" data-region-code="001" id="blockage_simulation" checked="" >
      </td>
    </tr>
    <tr id="">
      <td></td>
      <td></td>
      <td>
         <input type="checkbox" name="blockage_simulation[]" data-region-code="002" id="blockage_simulation" >
      </td>
    </tr>
  </tbody>
</table>

Code:

let regCodeAllRegions = [];
regCodeAllRegions = $('.settings-container').find('input:checkbox.changed').attr('data-region-code');
alert(JSON.stringify(regionCode));

CodePudding user response:

Method attr only works for a single element, so it returns only the last one. You need to iterate through the list. This is an example:

let regionCodes = [];

$('input:checkbox.changed').each((i, el) => regionCodes.push($(el).data('region-code')));

console.log(regionCodes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox"  data-region-code="1">
<input type="checkbox"  data-region-code="2">
<input type="checkbox"  data-region-code="3">
<input type="checkbox"  data-region-code="4">
<input type="checkbox"  data-region-code="5">

Another way:

let regionCodes = $('input:checkbox.changed').toArray().map((el) => $(el).data('region-code'));

console.log(regionCodes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox"  data-region-code="1">
<input type="checkbox"  data-region-code="2">
<input type="checkbox"  data-region-code="3">
<input type="checkbox"  data-region-code="4">
<input type="checkbox"  data-region-code="5">

  • Related