How to use jQuery to add a new row to a table, and assgin an incrementing id to it

后端 未结 3 963
春和景丽
春和景丽 2021-01-15 13:50

I have an existing HTML table, part of a form where the user enters GPS points. The user also has the option to upload GPS data points. I\'d like to have a button the user

3条回答
  •  天涯浪人
    2021-01-15 14:26

    Why use Jason's perfectly sensible solution when you could use an over-engineered version?

    ;o)

    function addRow() {
        var $newRow = $('#gpsTable tbody tr:last-child').clone();
        var newid = $newRow.children().eq(1).find('.StdTableData input').attr('id').match(/\d+/);
        newid = parseInt(newid[0]) + 1;
        var newXid = 'x' + newid;
        var newYid = 'y' + newid;
    
        $newRow.children().eq(0).find('.StdTableData').text(newid);
        $newRow.children().eq(1).find('.StdTableData input').attr({id:newXid,name:newXid}).val('');
        $newRow.children().eq(2).find('.StdTableData input').attr({id:newYid,name:newYid}).val('');
    
        $('#gpsTable tbody').append($newRow);
    }
    

    Oh, and just in case you're not quite so familiar with jQuery, here's some code that will turn your Sequence text heading into a button you can click to add a row.

    $(document).ready(function() {  
        $('th:first').click(function() {
            addRow();
        });
    });
    

提交回复
热议问题