简体   繁体   English

jQuery插入表行并增加输入ID

[英]Jquery insert table row and increment input id

I have a dynamic html table/form that has two buttons to add a row to the table. 我有一个动态的html表格/表单,该表单具有两个按钮以向表中添加一行。 One button adds a row to the end of the table and increments the input id appropriately. 一个按钮在表的末尾添加一行,并适当增加输入id。 The other button is intended to insert a row before the current row... which it can do until I attempt to have it increment the id. 另一个按钮用于在当前行之前插入一行...可以这样做,直到我尝试让它增加id为止。 My current jquery code updates the id appropriately but strips out the tags which results in all of the input fields being smashed into a single cell of the table. 我当前的jquery代码会适当地更新id,但会剥离标签,导致所有输入字段都被粉碎到表的单个单元格中。 I've included my existing code snippets below. 我在下面包括了我现有的代码片段。 . . what am I missing? 我想念什么?

link to fiddle 链接到小提琴

jquery code: jQuery代码:

$(document).on('click', 'button.insertbutton', function () {
    var rowCount = $('#orderDetail tr').length;
    alert(rowCount);
    $(this).closest('tr').before($(this).closest('tr').find('input')
        .each(function() {
        $(this).attr({
          'id':  function(_, id) { 
            var regex = /[a-zA-Z]+/
            return id.match(regex) + rowCount },
          //'name':  function(_, name) { return name + rowCount },
           'value': '',
        });
      })
    ).clone(true);
    return true;
});

I suspect the issue is within the section where I iterate through the input items and then clone back the row. 我怀疑问题出在我遍历输入项然后克隆回该行的部分中。

Any guidance would be much appreciated. 任何指导将不胜感激。

EDITED TO INCLUDE FIDDLE AS RECOMMENDED... THANK YOU FOR THE RECOMMENDATION. 编辑包括推荐内容...谢谢您的推荐。

I was able to solve the clone and increment ID by breaking up the operation into two steps vs trying to acomplish the task in a single line. 通过将操作分为两步,而不是尝试在一行中完成任务,我能够解决克隆和增量ID。 The jquery code for the insert and update id is as follows: 插入和更新ID的jquery代码如下:

$(document).on('click', 'button.insertbutton', function () {
var rowCount = $('#orderDetail tr').length;
$(this).closest('tr').before($(this).closest('tr').clone());
$(this).closest('tr').find('input').each(function() {
    $(this).attr({
        'id': function(_,id) {
            var regex = /[a-zA-Z]+/
            return id.match(regex) + rowCount },
        'value': '',
    })
})

return true;

}); });

I hope this helps someone in the future 我希望这对以后的人有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM