Im trying to do a copy of a row to add another line of inputs but every time i click the button the value of every input resets.
Here is what ive written so far:
<div style="margin-left: 2em;margin-right: 2em;">
<table class="table table-bordered">
<thead>
<tr>
>! th`s
</tr>
</thead>
<tbody id="aditional">
<tr id="template">
>! inputs and blank td`s
</tr>
<script>
const temp = document.getElementById("template").innerHTML;
const adit = document.getElementById("aditional");
function add() {
adit.innerHTML+='<tr>'+temp+'</tr>';
renum();
}
function renum() {
const lp = document.getElementsByClassName("lp");
for(let i=0;i<lp.length;i++) {
lp[i].innerHTML = i+1;
}
}
</script>
</tbody>
</table>
<button class="btn btn-success" type="button" onclick="add()">Dodaj</button>
</div>
Ive tried:
const temp = (document.getElementById("template").innerHTML).toString()
2
Answers
To prevent the input values from resetting, you should avoid directly manipulating the
innerHTML
, which causes the inputs to lose their values.You should use insertAdjacentHTML instead of innerHTML. It’s even clearly stated on the official documentation there:
That said, you can’t use
innerHTML
on table rows:As you see, the
div
returns its innerHTML just fine. The table row does not.