I'm relatively new to JS and my goal is to put focus on the input field if there is an error (after validation) and I realise that if I write onsubmit=validateFunction() directly in the HTML tag for form, (I assume) it refreshes the page and doesn't put the focus on the input field like how I wanted. Comparing this with calling it in JS, for eg, document.getElementById("myForm").onsubmit = validateFunction;
I will be able to get it to work like how I wanted it to. I don't understand the difference between the two, why does one (onSubmit in form tag) refreshes the page (or simply does not put focus on the input field) and the other (calling from JS) works like how I wanted it to?
Here is an example for more clarification on the question:-
function validateFunction() {
const name = document.getElementById("name");
if (name.length < 5) {
alert("Not valid!");
name.focus();
name.select();
return false;
} else {
return true;
}
}
<form id="myForm" action="" onsubmit="validateFunction();">
<label>Name: <input type="text" id="name"></label>
<button type="submit">Submit</button>
</form>
compared to (works):
<form id="myForm" action="">
<label>Name: <input type="text" id="name"></label>
<button type="submit">Submit</button>
</form>
<script type = "text/javascript" >
document.getElementById("myForm").onsubmit = validateFunction;
</script>