javascript - Jquery 添加和删除表格行

标签 javascript jquery html-table

我有一个 html 表,它使用 jQuery 动态添加和删除行。行数受 jQuery 计数器限制,允许用户最多添加 4 行。我的问题是,当用户创建第 4 行时,他们已达到限制,但当他们删除一行时,限制仍然存在,他们无法添加更多行。

http://jsfiddle.net/nallad1985/sqrrt/

HTML

<table id="myTable" class="order-list">
<thead>
    <tr>
        <td>Name</td>
        <td>Price</td>
    </tr>
</thead>
<tbody>
    <tr>
        <td>
            <input type="text" name="name" />
        </td>
        <td>
            <input type="text" name="price1" />
        </td>
        <td><a class="deleteRow"></a>
        </td>
    </tr>
</tbody>
<tfoot>
    <tr>
        <td colspan="5" style="text-align: left;">
            <input type="button" id="addrow" value="Add Row" />
        </td>
    </tr>
    <tr>
        <td colspan="">Grand Total: $<span id="grandtotal"></span>

        </td>
    </tr>
</tfoot>

JQUERY

$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
    var counter = $('#myTable tr').length - 2;
    var newRow = $("<tr>");
    var cols = "";

    cols += '<td><input type="text" name="name' + counter + '"/></td>';
    cols += '<td><input type="text" name="price' + counter + '"/></td>';

    cols += '<td><input type="button" id="ibtnDel"  value="Delete"></td>';
    newRow.append(cols);
    if (counter == 4) $('#addrow').attr('disabled', true).prop('value', "You've reached the limit");
    $("table.order-list").append(newRow);
    counter++;
});

$("table.order-list").on("change", 'input[name^="price"]', function (event) {
    calculateRow($(this).closest("tr"));
    calculateGrandTotal();
});

$("table.order-list").on("click", "#ibtnDel", function (event) {
    $(this).closest("tr").remove();
    calculateGrandTotal();
});

});

function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();

}

function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
    grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}

最佳答案

一系列修复,

  1. 删除了删除按钮的额外处理程序
  2. 将按钮 ID 更改为类别,因为您不应重复 ID。 Read why you should not duplicate ID .
  3. 添加了启用“添加行”按钮的逻辑。参见 Fixed fiddle
  4. 删除了 Add Row 处理程序中的 var 声明以更新全局变量

http://jsfiddle.net/sqrrt/2/

$("table.order-list").on("click", ".ibtnDel", function (event) {
    $(this).closest("tr").remove();
    calculateGrandTotal();

    counter -= 1
    $('#addrow').attr('disabled', false).prop('value', "Add Row");
});

关于javascript - Jquery 添加和删除表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16200104/

相关文章:

javascript - HTML 表格未按预期运行

javascript - 如何检查一个数字是否有两位小数并在必要时保留尾随零?

javascript - 为什么这个脚本不能在 Safari 或 Chrome 上运行?

javascript - 使用 jquery 将值传递给 popover 上的 iframe

html - 表格宽度比指定的像素长?

css - 表格布局和 CSS

c# - 即时搜索asp.net

javascript - 如何在每次点击时将 div 向左 move - 只需 javascript,无需 jquery

javascript - Safari ipad 上的错误 ScrollTop

jquery - 尝试在 css 中创建一个图像更改 div