Reputation: 477
I have an html table in my webpage. It is filled with information from my database.
It has this structure:
Id- Title –Author
1 – Africa – John Smith
2- Europe- Martin Coole
The table is inside a form and has an “Add More” button.
When you hit that button a modal window shows and you can append another title-author row to the table using:
//inside of the addRow function
$('#myTable').append(“<tr><td>..”);
The table also has an edit and delete button for each row. The onclick has:
//For the edit button
editRow(id, value1, value2);
//For the delete button
deleteRow(id);
And here comes my problem, the ids.
The info coming from the database has a solid id (1 and 2) but how should I deal with the ids of the rows appended with the “Add More” button?
What I have done so far is getting the last id from the database rows and put it in a hidden field in my table then in my js file:
var lastID = $('#lastID').val();
var i = 1;
var newId = parseInt (lastID)+i;
newId is 3 and this is valid if one row is appended but if a second row is appended via the “Add More” button I have 3 in newId again :((
How can I fix this? How can I add consecutive ids to the newly appended rows?
Upvotes: 1
Views: 213
Reputation: 173572
Keeping the last inserted id on the page is a bad idea; it's a kind of race condition. There are some approaches that could apply:
Inside addRow()
you communicate with the server directly and have it added; after the server inserted the record it will return the id and you can insert that inside your table.
Pros
Cons
You can simply mark the new records so that when you iterate over them to construct your AJAX request, you can send two separate lists to the server; one containing the existing ones (minus the deleted ones) and one containing only the new ones.
The server will then take care of the rest.
Upvotes: 1
Reputation: 136114
If, as you say on your comments, you're submitting the whole page together as sort of like a "Save everything" kind of operation, then newly added rows should NOT have an ID. Do not fall into the trap of trying to incrememnt the last known Id by 1, as 2 concurrent users will end up overwriting each other's record.
For new rows, the delete button is obvious, it just deletes the newly added row out of the table. For updates, just update the data in that row. These new rows could be given an id of 0
so that when you submit the page you know which ones are new (Id=0) and ones which are updates (Id>0).
Upvotes: 0
Reputation: 1044
During appending the new row, increment the lastId variable by 1.
A maybe better solution would be to recalculate the last Id by checking all rows in the table and update the variable.
Upvotes: 0
Reputation: 5910
In your function editRow
write:
var lastID = $('#lastID').val();
// Do your insertion stuff
// ...
// After insertion, raise lastID by 1
$('#lastID').val(++lastID);
Upvotes: 1