Mark checkboxes as indicated on a JSON

Asked

Viewed 345 times

-4

I have a table with two rows and three columns all with a checkbox set. The idea is to mark as checked through a json string var rs = [{"cklist":"1;1;1"},{"cklist":"0;0;0"}]; whereas the cklist[0] represents the ceckboxes in Row 1, and cklist[1] for Row 2. Ex: 1 means checked and 0 is not checked. Any idea how to make it work?

tried the code below and all columns in row 1 should be checked and only the 2nd column is checked.

var rs = [{"cklist":"1;1;1"},{"cklist":"0;0;0"}];
/*primeiro row dos checkboxs deveriam ficar checked 
   conforme z = rs[p].cklist.split(';');
   */
var rows = 2;

for(i=0;i<rows;i++){
  for(p=0;p<30;p++){ 

    var z = rs[p].cklist.split(';');
    for(j=0; j<z.length;j++){

      //set checkbox true ou false
      if( z[j] == 0 ){ var zz = 'false'; }else{ var zz = 'true';} 

      $('#tts'+p+' td:eq('+p+') input:checkbox').attr("checked", zz);
      //alert(zz )
    }
  }

}
<table>
  <tr id='tts1'>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
  <tr id='tts2'>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
</table>

  • 1

    When you write for(p=0;p<30;p++){ this implies that rs has to have at least 29 objects inside. I only see 2... that’s problem number 1 in my view.

1 answer

0

Just like @Sergio pointed out, your ties don’t make any sense.

In any case, you just need to scroll through each element of the Array rs, then go through the values of each object.cklist.split(";").

Since the Array has the same number of elements as rows in the table, and each object in the array can be divided into number similar to the columns, then it is easy to interact both.

var tb = document.querySelector("table");
var rs = [{"cklist":"1;1;1"},{"cklist":"0;0;0"}];

for (var i = 0; i < rs.length; i++) {
  var cklist = rs[i].cklist.split(";");
  var cboxes = tb.rows[i].querySelectorAll("[type='checkbox']");      
  for (var j = 0; j < cklist.length; j++) {
    cboxes[j].checked = cklist[j] == 1;
  }
}
<table>
  <tr id='tts1'>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
  <tr id='tts2'>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
</table>

  • That’s exactly what I wanted. Only the logical reasoning didn’t fit. Thanks for the attention. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.