Check boxes values returned and added to string

102 Views Asked by At

I am trying to take a row of checkboxes in a table and for each TD in the table it needs to check if the checkbox is ticked, is so it is a 1 and else its 0. I need a for loop where I will be able to loop over each td, determin if it is checked and if so add a 1 to a binary string or else add a 0 to the binary string.

This should end with each tr having its own unique binary string from the checkboxes that have or have not been ticked. I will also want to set up each tr with its own unique ID.

The below code is what I have so far but am presumming I am going in the wrong direction.

Any help appreciated. Thanks

[ { ID: 000, binary: 0101010101 }  ]
function generate(){


$("#actionTable>tbody").children("tr").each(function(i, rowitem){
    $(rowitem).children("td").each(function(index, item){
        if (index == 0){
            var amid = $(item).data("amid");
        }

        else {
            //Handle checkbox
            var checked = $(item.firstChild).prop('checked')
        }
    });
});

}

1

There are 1 best solutions below

0
On

You can use a nested map() for this. The outer map iterates rows

The inner map iterates each input's checked property converted to number and then to string and then joins the array for final string.

I don't know what the html looks like so have just used the row index of each row for now

const res = $('tr').map((i, el) => {

  const binary = $(el).find(':checkbox').map((_, inp) => {
      return `${+inp.checked}`;
  }).get().join('');
  
  return { index: i, binary};
  
}).get()

console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="checkbox"></td>
    <td><input type="checkbox" checked></td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
  <tr>
    <td><input type="checkbox" checked></td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox" checked></td>
    <td><input type="checkbox"></td>
  </tr>
</table>