u936293
u936293

Reputation: 16264

Invoking the focus method causes onblur to fire endlessly

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

Answers (3)

Jeyanth
Jeyanth

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

Alonad
Alonad

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.

  1. Input gets onblur event, shows alert, automatically focuses on input.
  2. You click anywhere and onblur fires again, shows alert, and focuses on input again.

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

Christoph
Christoph

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

Related Questions