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

后端 未结 3 964
春和景丽
春和景丽 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:09

    A partial solution to your problem (if you don't want to parse ids) could be to create a hidden input to store the last numeric portion of your ID value which you could use to increment your table ID while incrementing the hidden input value as well. As for inserting a table line, that's pretty straightforward JS. Create your tr element, create your td elements, populate them, append to your tr, append tr to table. Done.

    0 讨论(0)
  • 2021-01-15 14:23

    This should work for adding a single row. You could wrap it in some sort of loop to add multiple:

    function AddRow(xValue,yValue)
    {
    var index = $("#gpsTable tr:last td:first").text();
    var newIndex = parseInt(index) + 1;
    var rowHtml = '<tr><td class="zSmall" style="text-align: right;"><div class="StdTableData">' + newIndex + '</div></td>';
    rowHtml += '<td class="zSmall"><div class="StdTableData"><input type="text" name="x' + newIndex + '" id="x' + newIndex + '" size="8" maxlength="16" value="' + xValue + '"/></div></td>';
    rowHtml += '<td class="zSmall"><div class="StdTableData"><input type="text" name="y' + newIndex + '" id="y' + newIndex + '" size="8" maxlength="16" value="' + yValue + '"/></div></td></tr>';
    
    $("#gpsTable tr:last").after(rowHtml);
    return false;
    }
    
    0 讨论(0)
  • 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();
        });
    });
    
    0 讨论(0)
提交回复
热议问题