Search code examples
javascriptjqueryhtmlalertonblur

Onblur giving continuous alert in loop when clicked from 1 textbox to another


I am currently calling an on blur function for all textboxes,like below:

<input type="text" id="fname" onblur="myFunction()">
<input type="text" id="fname2" onblur="myFunction()">

which validates the input provided and gives an alert in case of mismatch. The issue I am facing here is When the user blurs from 1 textbox and directly focusing to another checkbox. The Alert continuously apprears. because it considers the click of ok of the alert as a blur of the textbox. I could use onchange. But onchange is giving me an issue in IE. I have duplicated a sample code here:

function myFunction() {
  alert("Value Changed");
}
Enter your name:
<input type="text" id="fname" onblur="myFunction()">
<input type="text" id="fname2" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>


Solution

  • Don't use alert (or its cousins confirm and prompt) in blur or focus events. Their odd 1990's focus-stealing, world-stopping behavior and its interplay with the blur and focus events varies from browser to browser.

    Use a modern mechanism for displaying the message via the DOM, rather than alert.

    In a comment you've said:

    But i need to ask a confirmation from the user here...

    There are lots of ways to do that within the DOM. You can either code them yourself or use any of several libraries that do a lot of the heavy-lifting for you.