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]
innerHTMLis NOT the way to go with your scenario. You really should be using theinsertRowandinsertCellmethods provided by Javascript. Is it much cleaner, maintainable, and easier to read.innerHTMLoverwrites 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 timeaddRowis 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
addRowis called. You can just useinsertRowand 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:
http://jsfiddle.net/MJ2md/
To demonstrate what I mean. It may not be the cleanest, I just wanted to write it up fast!