Reputation: 73
I have written code that adds a new row in the table when the button is clicked. If I enter values and then click the button, the data is deleted. Why?
document.getElementById('add').addEventListener('click', function(){
document.querySelector('table tbody').innerHTML += document.querySelector('table tbody tr').innerHTML;
});
<button id="add">Add</button>
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="checkbox" checked></td>
</tr>
</tbody>
</table>
Upvotes: 1
Views: 84
Reputation:
You might want to consider using the append() method.
<body>
<button id="add">Add</button>
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody id="tableBody">
<tr>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="checkbox" checked></td>
</tr>
</tbody>
</table>
<script>
let count = 0;
function newInputElement(type, placeholder="", min=1) {
let input = document.createElement('input');
input.type = type;
input.id = type + count;
if(type == 'number') {
input.placeholder = placeholder;
input.min = min;
} else {
console.log("add another type for support");
}
count++;
return input.outerHTML;
}
function addNewRowOfInputs(target, destination, triggerEvent) {
document.getElementById(target).addEventListener(triggerEvent, function() {
let row = document.createElement('tr');
row.innerHTML =
'<tr>' +
'<td>' + newInputElement('number', 'test') + '</td>' +
'<td>' + newInputElement('number', 'test') + '</td>' +
'<td>' + newInputElement('number', 'test') + '</td>' +
'<td>' + newInputElement('number', 'test') + '</td>' +
'<td><input type="checkbox" checked></td>' +
'<tr>';
document.getElementById(destination).append(row);
});
}
addNewRowOfInputs('add', 'tableBody', 'click');
</script>
</body>
By doing this, you can add on to the existing content without overwriting it's content.
Upvotes: 2