I am creating a table based on result from servlet, which contains a checkbox , when the checked property of checkbox is true there will be one button in the bottom of the table which calls for a remove function, which removes that particular row from table, this function is working when the table is created inside jsp using server tags, but when it is created from jQuery .getJSON method, it is not working. The code is.
var contents="";
$.getJSON("trnReceipt?caseNo=21&insid="+cdid.text(),function(datalist) {
$.each(datalist, function(index, data) {
contents += '<tr><td><input type="hidden" id="txt_select'+index+'" name="txt_select'+index+'" value='+data.return_status+'></input><input type="checkbox" name="chk_select'+index+'" /></td><td><input type="hidden" name="txtInstrid'+index+'" value="'+data.Instrumentid+'"/>' + data.Instrumentid + '</td></tr>';
index++;
})
$('#tblDetails').append(contents);
})
The Javascript code to delete the row is:
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
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) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch(e) {
alert(e);
}
}
Where I am making a mistake?
The first node in your td tag is the hidden field, not a checkbox. So, in the rows that come from the getJson method, the chkbox variable is not actually your checkbox, and hence the criteria for deleting the row will always be false.
As long as you’re already using jQuery, consider using jQuery for the actual delete. It will be much shorter and actually less prone to errors.