Reputation: 640
I'm trying to create text box in a table on button click. I've wrote javascript code in the button click and it works. My problem is that data entered in the textbox of previous row is cleared when adding next row of textbox. Code and screen shots are given. Please help to solve this problem.
function addRow(tableID) {
var table = document.getElementById(tableID);
var count = table.rows.length - 1;
table.innerHTML += "<tr> <td>"+count+"</td> <td><input type='text' id='date" + count + "' size='20'></td> <td><input type='text' id='from" + count + "' size='20'></td> <td><input type='text' id='to" + count + "' size='20'></td> <td><input type='text' id='mode" + count + "' size='20'></td> </tr>";
}
on clicking add button I lose data curresponding to Sl.no1]
Upvotes: 2
Views: 262
Reputation: 50905
innerHTML
is NOT the way to go with your scenario. You really should be using the insertRow
and insertCell
methods provided by Javascript. Is it much cleaner, maintainable, and easier to read. innerHTML
overwrites the element's contents, which is your problem. If you used .innerHTML += "something"
then it might work, but then you can't construct your table every time addRow
is called - you would just literally append a new row via HTML.
https://developer.mozilla.org/en-US/docs/DOM/table.insertRow
https://developer.mozilla.org/en-US/docs/DOM/tableRow.insertCell
This way, you don't have to completely construct the table every time the function addRow
is called. You can just use insertRow
and append a new one with a textbox inside. Your previous rows won't be overwritten, recreated, or messed up at all (as long as you do it right). Although there are examples in the links, I'll post an example with your code in a few minutes.
UPDATE:
To demonstrate what I mean. It may not be the cleanest, I just wanted to write it up fast!
Upvotes: 4