Hello to everyone, my problem is, Im creating dynamacly rows in a table with a textfield and a checkbox, but to delete the rows the checkbox must be on the first column witch I dont get it, if I move the checkbox to the last column and press it, javascript associates that the checkbox is not checked! How can this be fixed? Do I need to loop through the elements of the row ?

This is the code to add a row:

<script>

var intTextBox=0;
  $(function(){
    var tbl = $("#Tablei");

    $("#addRowBtn").click(function(){
        intTextBox = intTextBox + 1;
        var contentID = document.getElementById('content');
        var newTBDiv = document.createElement('div');
        newTBDiv.setAttribute('id','strText'+intTextBox);
        $("<tr><td><input type='text' name='txt[]' id='"+intTextBox+"'></td><td><input type='checkbox' name='chk'/></td></tr>").appendTo(tbl);  
        contentID.appendChild(newTBDiv); 

        });
    });    

</script>

This is the code to delete a row:

<script>
function myFunction(){
      try {
          var table = document.getElementById('Tablei');
          // var table = x.getAttribute("id");
          var rowCount = table.rows.length;

          for(var i=0; i<rowCount; i++){
              var row = table.rows[i];
              var chkbox = row.cells[0].childNodes[0];

              if(null != chkbox && true == chkbox.checked) {
                  alert("a");
                  if(rowCount <= 1) {
                      alert("Cannot delete all the rows.");
                      break;
                  }
                  table.deleteRow(i);
                  rowCount--;
                  i--;
              }
           }
       }
       catch(e) {
           alert(e);
       }
}
</script>
Member Avatar for LastMitch

but to delete the rows the checkbox must be on the first column witch I dont get it, if I move the checkbox to the last column and press it, javascript associates that the checkbox is not checked!

You can try this:

$('#Tablei input[type=checkbox]:checked').each(function() { 
   var row = $(this).parent().parent();
   var rowcells = row.find('td');
});

<table><tr><td><input type="checkbox" name="Tablei" checked></td></tr></table>

Then to delete you can keep the code intact and modify it a little so you can delete the <td>

Hi LastMitch, sorry for not replying for 2 FULL WEEKS, I forgot about this issue of mine, last night I picked it up and I was able to get it to work! Thank you for helping :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.