TechTotie TechTotie - 5 months ago 10
HTML Question

Form submit without redirection and reloading

I am new to HTML. I have written an app, which allows user to add data and it's a local application. I have used forms int this application and I am facing a problem when form submission happens. I don't want the page to navigate/redirect and even don't want the same page to reload. Currently it's reloading the page. Please let me know what stops redirecting/reloading this app. I don't want any php code, application needs to be pure HTML and JS only.
Below is the HTML app code.



function addInfo() {
var InfoForm = document.forms["InfoForm"];
var trelem = document.createElement("tr");
for (var i = 0; i < InfoForm.length - 1; i++) {
var tdelem = document.createElement("td");
tdelem.innerHTML = InfoForm[i].value;
trelem.appendChild(tdelem);
}
document.getElementById("current_table").appendChild(trelem);
return false;
}

function done(e) {
e.preventDefault();
return false;
}

<div id="current_div">
<h2>Table Heading</h2>
<table border="1" id="current_table">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
</div>

<div id="input_div">
<form name="InfoForm" accept-charset="utf-8" onsubmit="done(e)">
Name :
<input type="text" name="Name" value="">
<br>
<br>Age :
<input type="number" name="Age" value="">
<br>
<br>
<input type="submit" value="Add_Info" onclick="addInfo()">
</form>

</div>




Answer

This is not the right case to use a <form>. A <form> is used when you send via GET or POST method data to the server.

Therefore just use a <button> and two <input>.

It's easier to insert a row with insertRow and insertCell.

Complete example :

var nName = document.getElementById("nName");
var nAge = document.getElementById("nAge");
var btn = document.getElementById("addData");
var tbl = document.getElementById("myData");

function addData() {
  var row = tbl.insertRow(0);
  var d1 = row.insertCell(0);
  var d2 = row.insertCell(1);
  d1.innerHTML = nName.value;
  d2.innerHTML = nAge.value;
}

btn.addEventListener("click", addData);
table {
  margin: 15px 0;
}
#inputData > div {
  margin: 5px 0;
}
#inputData > div > span {
  display: inline-block;
  width: 100px;
}
<table border="1">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody id="myData"></tbody>
  <!-- Insert data -->
</table>
<div id="inputData">
  <div><span>Name:</span>
    <input type="text" id="nName">
  </div>
  <div><span>Age:</span>
    <input type="number" id="nAge">
  </div>
  <div>
    <button id="addData">Add data</button>
  </div>
</div>

Comments