Reputation: 16264
I want to validate an input box when the user moves on to another field. I have the following code which works fine.
validate = (v) => {
if (v.value=="yes") return;
alert("Value must be exactly 'yes'. Please rectify.");
//v.focus();
}
<p>Enter only 'yes' in this field:</p>
<input onblur='validate(this);' />
However, if I add invoking the focus
method with the intention to highlight to the user to fix the error before continuing, the onblur
method is fired endlessly. Why is this so?
The fiddle is https://jsfiddle.net/OldGeezer/8xfLwvn6/4/
On further testing, I find that the endless onblur
does not happen if it loses focus because I click on another application window. It happens if I simply click another part of the web page (in Chrome).
Upvotes: 1
Views: 1938
Reputation: 641
Using alert()
removes focus from the active element which causes blur
to trigger. Thereby, according to your script , blur
triggers continuously. Use console.log()
which helps you to understand about this much better.
Upvotes: 3
Reputation: 2256
What you are doing is constantly run onblur function, you run it again and again and on each iteration it gives you alert.
And you do it in a loop so to say.
Instead of focusing on input, you can just give it border color. This way your onblur will fire once only.
Upvotes: 0
Reputation: 281
According to w3schools:
Note: The alert box takes the focus away from the current window, and forces the browser to read the message. Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.
Link: https://www.w3schools.com/jsref/met_win_alert.asp
Alert takes focus away from the input creating an endless loop. The solution is to display the message in a different way. For example in a span element:
<p>Enter only 'yes' in this field:</p>
<input onblur="validate(this);" />
<span id="message"></span>
<script>
validate = (v) => {
if (v.value=="yes") return;
document.getElementById("message").innerHTML = "Value must be exactly 'yes'. Please rectify.";
v.focus();
}
</script>
Upvotes: 1