Mark checkboxes as indicated in a JSON

-4

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

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

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>
    
asked by anonymous 23.02.2016 / 02:38

1 answer

0

As @Sergio pointed out, their ties do not make the slightest sense.

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

As Array has the same number of elements as rows in the table, and each object in the array can be divided into a number similar to columns, then it is easy to interact with 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>
    
23.02.2016 / 13:11