开发者

Unable to remove row from table created by jQuery

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?


You can use jQuery to delete the rows like this:

$('#' + tableId + ' tr:has(td :checkbox:checked)').remove();

This will delete all rows that contain a checked checkbox.

Your problem is probably that you're looking in the wrong cell.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜