Harpreet Singh Harpreet Singh - 1 month ago 9
HTML Question

Data disappears after a split second using JS to render form data on same page

I was trying to render form data on the same page using JavaScript.

JavaScript

function renderInput(age) {
document.getElementById('display').innerHTML += age;
}


It works when the submit button is placed outside the form element.

HTML - When it works

<form>
<label><b>Enter your age</b></label>
<input type="text" name="age" id="user_input">
</form>

<input type="submit"
onclick='renderInput(document.getElementById("user_input").value);'><br/>

<div id='display'>Your age is </div>


While it renders the the div with the id "display" just for a split second and then disappears if the submit field is placed inside the form element.

HTML - When it doesn't work

<form>
<label><b>Enter your age</b></label>
<input type="text" name="age" id="user_input">
<input type="submit"
onclick='renderInput(document.getElementById("user_input").value);'><br/>
</form>

<div id='display'>Your age is </div>


I can't seem to get my head around this. Why is this happening?

jkp jkp
Answer

You should stop the form from submitting, by returning false with the onclick event like this:

<input type="submit" onclick='renderInput(document.getElementById("user_input").value); return false;'>