如何使用jQuery删除已检查的表行

时间:2014-02-02 07:27:29

标签: jquery

我正在尝试删除已选中复选框的表行。这是我可以向表添加行的代码,但我不知道如何仅删除已选中的行。

$( document ).ready(function() {
  $("#add").on("click",function(){
  $('table').append('<tr> <td><input type="checkbox" name="vehicle" value="Bike"></td><td>Color Option : <input type="color" name="favcolor"></td><td>Item ID: <input type="text" name="firstname"></td> </tr>');
});
});

请您查看This Demo并告诉我如何仅删除选中的行

4 个答案:

答案 0 :(得分:4)

删除按钮的ID中有一个尾随空格将其删除

<button id="remove" type="button">Reomve Selected Color</button>

然后添加一个点击处理程序并使用.has()查找带有选中复选框的行

$("#remove").on("click", function () {
    $('table tr').has('input[name="vehicle"]:checked').remove()
})

演示:Fiddle

答案 1 :(得分:2)

使用:

  $("#remove").on("click",function(){
     $('input:checked').each(function() {
     $(this).closest('tr').remove();
      });
 });

<强> Working Fiddle

答案 2 :(得分:0)

你应该删除所有输入

$("tr input[type='chekbox']:cheked").remove()

答案 3 :(得分:0)

删除行

按钮的HTML(为实际的表ID更改'myTable')

<input id="removeRowBtn" onclick="deleteRow('myTable')" value="Remove selected row" name="removeRowBtn" type="button">

Javascript(带有额外的fadeOut效果)

var deleteRow = function(tableID) {
    var ID = "#" + tableID;
    var rowCount = jQuery(ID + " tbody tr").length;

    jQuery(ID + " input:checked").each(function() {

        if (rowCount > 1)
        {
            jQuery(this).closest('tr').fadeOut(function () { 
                jQuery(this).remove();
            });
            rowCount--;
        }
        else
            alert("Cannot remove all rows.");
    });

    return false;
}

添加/复制行(额外,不是答案)

按钮的HTML(为实际的表ID更改'myTable')

<input id="addRowBtn" onclick="addRow('myTable')" value="Add row" name="addRowBtn" type="button">

Javascript(复制第一行,带有淡入淡出效果)

var addRow = function(tableID) {
    var ID = "#" + tableID;
    var rowCount = jQuery(ID + " tbody tr").length;
    if (rowCount < 5) { // limit the user from creating more rows
        jQuery(ID + " tbody tr:first").clone().appendTo(ID).hide().fadeIn();
    } else {
        alert("Cannot add more than 5 rows.");
    }
    return false;
}

注意:由于可能的冲突,我使用jQuery而不是$。代码假定您的行也在tbody内,遵循HTML5标准并避免与thead或tfoot发生冲突。我也知道使用click事件代替html属性onclick可能更干净,但这也有它的优点。至少可以帮助别人。