I am trying to validate a form using a JavaScript function. I think it works, but the output disappears almost immediately.
Here is the relevant code:
<form name="myForm">
Your Age: <input type="text" name="age">
<input type="submit" value=" Send " id="submit">
</form>
document.getElementById("submit").addEventListener("click", validate);
function validate () {
var x = document.forms["myForm"]["age"].value;
if (x > 0) {
document.getElementById("demo").innerHTML = "Congrats you have entered x, your answer has been submitted";
}
else {
document.getElementById("demo").innerHTML = "ERROR: Please enter a valid age";
return false;
}
}
What ya think boys?
event.preventDefault()? Also, it's generally better to validate in response to the form element'ssubmitevent rather than a button click.return falsedoesn't work from within an event handler bound withaddEventListener(). (It does work from event handlers bound via older techniques, but those are generally frowned upon these days. Stick with.addEventListener()and useevent.preventDefault().)