jQuery添加和删除动态表格行

26

我可以为表格添加很多行,但我无法删除很多行。我每次只能移除一个连续添加的行。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" id="remCF">Remove</a></td></tr>');
        $("#remCF").on('click',function(){
            $(this).parent().parent().remove();
        });
    });
});
</script>

<table class="form-table" id="customFields">
<tr valign="top">
    <th scope="row"><label for="customFieldName">Custom Field</label></th>
    <td>
        <input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp;
        <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp;
        <a href="javascript:void(0);" id="addCF">Add</a>
    </td>
</tr>
</table>
你可以在http://jsfiddle.net/3AJcj/查看代码。
我需要帮助。
11个回答

50

每个网页只能拥有一个唯一的ID,将这些ID更改为类,并同时更改jQuery选择器。

此外,将.on()移出.click()函数,因为您只需要设置一次。

http://jsfiddle.net/samliew/3AJcj/2/

$(document).ready(function(){
    $(".addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
    });
    $("#customFields").on('click','.remCF',function(){
        $(this).parent().parent().remove();
    });
});

谢谢,它真的有效。 但是如果我使用.live(),它也可以工作,但需要旧版本的jQuery库http://jsfiddle.net/gfpoow/fgZF3/。 - user770668

11
您可以使用jQuery在图像中展示的方式动态添加和删除表格行,如下所示... 在这里输入图片描述 这是HTML部分...
<form id='students' method='post' name='students' action='index.php'>

    <table border="1" cellspacing="0">
      <tr>
        <th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
        <th>S. No</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Tamil</th>
        <th>English</th>
        <th>Computer</th>
        <th>Total</th>
      </tr>
      <tr>
        <td><input type='checkbox' class='case'/></td>
        <td>1.</td>
        <td><input type='text' id='first_name' name='first_name[]'/></td>
        <td><input type='text' id='last_name' name='last_name[]'/></td>
        <td><input type='text' id='tamil' name='tamil[]'/></td>
        <td><input type='text' id='english' name='english[]'/> </td>
        <td><input type='text' id='computer' name='computer[]'/></td>
        <td><input type='text' id='total' name='total[]'/> </td>
      </tr>
    </table>

    <button type="button" class='delete'>- Delete</button>
    <button type="button" class='addmore'>+ Add More</button>
    <p>
    <input type='submit' name='submit' value='submit' class='but'/></p>
</form>

下一步需要包含 jQuery...

<script src='jquery-1.9.1.min.js'></script>

最后,添加表格行的脚本...

<script>
  var i=2;
  $(".addmore").on('click',function(){
    var data="<tr><td><input type='checkbox' class='case'/></td><td>"+i+".</td>";
        data +="<td><input type='text' id='first_name"+i+"' name='first_name[]'/></td> <td><input type='text' id='last_name"+i+"' name='last_name[]'/></td><td><input type='text' id='tamil"+i+"' name='tamil[]'/></td><td><input type='text' id='english"+i+"' name='english[]'/></td><td><input type='text' id='computer"+i+"' name='computer[]'/></td><td><input type='text' id='total"+i+"' name='total[]'/></td></tr>";
        $('table').append(data);
        i++;
});
</script>

也可以参考演示教程来动态添加和删除表格行。


4

将ID改为class:

$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');

$(".remCF").on('click',function(){
            $(this).parent().parent().remove();
        });

http://jsfiddle.net/7BHDm/1/


4
除了其他答案之外,我想改进移除功能,使其更加通用:
$(this).closest('tr').remove();

这比使用 $(this).parent().parent().remove(); 更好,因为它不依赖元素的深度。所以,行的结构变得更加灵活。

3

这里有多个问题

  1. 在页面中,id应该是唯一的。
  2. 对于动态元素,需要使用.on()进行事件委托。

示例

$(document).ready(function(){
    $("#addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" id="remCF">Remove</a></td></tr>');
    });

    $("#customFields").on('click', '#remCF', function(){
        $(this).parent().parent().remove();
    });

});

演示:Fiddle

查看此演示,其中已删除id属性。

$(document).ready(function(){
    $("#addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
    });

    $("#customFields").on('click', '.remCF', function(){
        $(this).parent().parent().remove();
    });

});

2

实时预览 Jsfiddle链接

非常简单的方法可以解决它......看一下我新收集的代码。

 $(document).ready(function(){
            $(".add-row").click(function(){
                var name = $("#name").val();
                var email = $("#email").val();
                var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
                $("table tbody").append(markup);
            });

            // Find and remove selected table rows
            $(".delete-row").click(function(){
                $("table tbody").find('input[name="record"]').each(function(){
                    if($(this).is(":checked")){
                        $(this).parents("tr").remove();
                    }
                });
            });
        });   

$(document).ready(function() {
  $(".add-row").click(function() {
    var name = $("#name").val();
    var email = $("#email").val();
    var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
    $("table tbody").append(markup);
  });

  // Find and remove selected table rows
  $(".delete-row").click(function() {
    $("table tbody").find('input[name="record"]').each(function() {
      if ($(this).is(":checked")) {
        $(this).parents("tr").remove();
      }
    });
  });
});
form {
  margin: 20px 0;
}
form input,
button {
  padding: 6px;
  font-size: 18px;
}
table {
  width: 100%;
  margin-bottom: 20px;
  border-collapse: collapse;
  background: #fff;
}
table,
th,
td {
  border: 1px solid #cdcdcd;
}
table th,
table td {
  padding: 10px;
  text-align: left;
}
body {
  background: #ccc;
}
.add-row,
.delete-row {
  font-size: 16px;
  font-weight: 600;
  padding: 8px 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" id="name" placeholder="Name">
  <input type="text" id="email" placeholder="Email">
  <input type="button" class="add-row" value="Add Row">
</form>
<table>
  <thead>
    <tr>
      <th>Select</th>
      <th>Name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="checkbox" name="record">
      </td>
      <td>Peter Parker</td>
      <td>peterparker@mail.com</td>
    </tr>
  </tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>


1
请尝试一下:
<script>
$(document).ready(function(){
    var add = '<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td>';
                add+= '<input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" />&nbsp;&nbsp;&nbsp;';
                add+= '<input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" />&nbsp;';
                add+= '<a href="javascript:void(0);" class="remCF">Remove</a></td></tr>';

    $(".addCF").click(function(){ $("#customFields").append(add); });

    $("#customFields").on('click','.remCF',function(){
        var inx = $('.remCF').index(this);
        $('tr').eq(inx+1).remove();
    });
});
</script>

请格式化您的代码以使其更易读。您可以查看此Markdown帮助页面。除了格式化之外,如果您能添加描述而不仅仅是代码,那将会很好。 - Dennis van der Schagt

1
<script>
    $(document).ready(function(){
        var add = '<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td>';
        add+= '<input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" />&nbsp;&nbsp;&nbsp;';
        add+= '<input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" />&nbsp;';
        add+= '<a href="javascript:void(0);" class="remCF">Remove</a></td></tr>';

        $(".addCF").click(function(){ $("#customFields").append(add); });

        $("#customFields").on('click','.remCF',function(){
            var inx = $('.remCF').index(this);
            $('tr').eq(inx+1).remove();
        });
    });
</script>

0
   // dynamically generate row by clicking plus icon
        $(document).on('click', '.add_row', function (e) {
            e.preventDefault();
            var configParamsObj = {
                placeholder: 'Select an option...', // Place holder text to place in the select
                minimumResultsForSearch: 3 // Overrides default of 15 set above
            };
            var $thisTable = $(this).closest('table').find('tbody');
            var copyRow = $thisTable.find('tr:first');
            var hasSelect2 = $thisTable.find('.singleSelectExample').length;
            if (hasSelect2 !== 0) $thisTable.find(".singleSelectExample").select2('destroy');
            $thisTable.prepend(`<tr>${copyRow.html()}</tr>`);
            if (hasSelect2 !== 0) {
                $thisTable.find('.singleSelectExample').select2().next().next().remove();
                $thisTable.find('select.singleSelectExample').select2(configParamsObj);
            }
            var $thisRow = $thisTable.find('tr:first');
            $thisRow.find('select').val('').trigger('change');
            $thisRow.find("input.datepicker").each(function (i, key) {
                var format = $(key).data('format');
                $(key).datetimepicker({
                    format: format,
                    showClear: true
                });
            });
            $thisRow.find("input.customdatepicker").each(function (i, key) {
                var format = $(key).data('format');
                $(key).datetimepicker({
                    format: format,
                    showClear: true,
                    minDate: new Date()
                });
            });
            $thisRow.find("input[type=text]").val("");
            $thisRow.find("input[type=hidden]").val("");
            $thisRow.find("input[type=number]").val("");
        });

        // remove added rows
        $(document).on("click", "a.removeRow ", function (e) {
            e.preventDefault();
            var thisRow = $(this).closest("tr");
            var totalRows = thisRow.closest('tbody').find('tr').length;
            if (totalRows > 1) thisRow.remove();
        });

0
$(document).ready(function () {
    Addrow();
})
$("#add").click(function () {
    Addrow();
})
rowcount = $("#tbuser td").closest.length;
function Addrow() {
    rowcount++;
    debugger
    var markup = "<tr><td></td><td><input type='text' name='stuclass' id='stuclass'/></td><td><select name='Institute' class='Institute_" + rowcount + "'></select></td><td><input type='text' name='obtmark' id='obtmark'/></td><td><input type='text' name='totalmark' id='totalmark'/></td><td><input type='text' name='per' id='per'/></td><td><button type='button' id='delete' onclick='deleterow(this);'>DELETE</button></td></tr>";
    $(".tbuser tbody").append(markup);

    $.ajax({
        type: 'GET',
        url: '@Url.Action("bindinst", "Home")',
        data: '',
        dataType: "json",
        success: function (data) {
            debugger;
            $(".Institute_" + rowcount).empty();
            $(".Institute_" + rowcount).append('<option Value="">--Select--</option>');
            $.each(data, function (i, result) {

                $(".Institute_" + rowcount).append('<option Value="' + result.Value + '">' + result.Text + '</option>');
            });
        },

    });


}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接