Ken Ken - 1 month ago 16
HTML Question

row insertion in html table

I created this html form.

<form id="formu">
<label for="n" >First Name : </label><input type="text" id="n"/><br/>
<label for="p" >Last Name : </label><input type="text" id="p"/><br/>
<button type="submit">Save</button>
</form>


when the form is submitted, i want to add informations provided by the user to a table. the table code is :

<table id="tab" border="1">
<tr>
<td>Id</td>
<td>Last Name</td>
<td>First Name</td>
</tr>
</table>


this is the javascript code for the form submission

<script type="text/javascript">
var fo = document.getElementById("formu");


fo.addEventListener("submit",function()
{
var tab=document.getElementById("tab");

var lign = tab.insertRow();

var id1 = lign.insertCell(0);

var nom = lign.insertCell(1);

var prenom = lign.insertCell(2);

id1.innerHTML="1";
nom.innerHTML=document.getElementById("n").value;
prenom.innerHTML=document.getElementById("p").value;

});

</script>


but once the form is submitted, the submited data appear in the tbale and disapear just after.

Answer

The reason why the data is disappearing is that by using a standard form the page will refresh as the form is submitted to itself.

To prevent this, you need to use preventDefault() in your function, for example:

fo.addEventListener("submit",function(e)
    {
        e.preventDefault();
        var tab=document.getElementById("tab");

        var lign = tab.insertRow();

        var id1 = lign.insertCell(0);

        var nom = lign.insertCell(1);

        var prenom = lign.insertCell(2);

        id1.innerHTML="1";
        nom.innerHTML=document.getElementById("n").value;
        prenom.innerHTML=document.getElementById("p").value;

    });