How To Use Jquery To Add A New Row To A Table, And Assgin An Incrementing Id To It
Solution 1:
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();
});
});
Solution 2:
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.
Solution 3:
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><tdclass="zSmall"style="text-align: right;"><divclass="StdTableData">' + newIndex + '</div></td>';
rowHtml += '<tdclass="zSmall"><divclass="StdTableData"><inputtype="text"name="x' + newIndex + '"id="x' + newIndex + '"size="8"maxlength="16"value="' + xValue + '"/></div></td>';
rowHtml += '<tdclass="zSmall"><divclass="StdTableData"><inputtype="text"name="y' + newIndex + '"id="y' + newIndex + '"size="8"maxlength="16"value="' + yValue + '"/></div></td></tr>';
$("#gpsTable tr:last").after(rowHtml);
return false;
}
Post a Comment for "How To Use Jquery To Add A New Row To A Table, And Assgin An Incrementing Id To It"