Consider this code:
var input = document.getElementById("hello");
input.addEventListener('blur', function() {
alert('hello');
input.select();
input.focus();
});
<input type="text" value="hello" id="hello" />
The idea around it is to keep the user focused in the input until he/she enters a valid text in it. This is a simplified version of the code.
Js fiddle here: https://jsfiddle.net/wzwft49w/9/
Problem: If you focus on the input and then blur it, you will get an infinite alert popup in Chrome but not in IE.
1. How would you solve this problem?
2. Any ideas on why does this happen?
Notes:
Here is my solution for chrome:
var inputs = document.querySelectorAll("input"),
len = inputs.length,
i;
var gflag=false;
function myalert(m,o) {
if (gflag) {
return;
}
gflag=true;
alert(m);
o.focus();
setTimeout(function() {gflag=false;},10);
}
function makeBlurHandler() {
"use strict";
return function () {
if (this.value === "") {
myalert("Cannot be blank!",this);
this.nextElementSibling.innerHTML = "Cannot be blank!";
} else {
this.nextElementSibling.innerHTML = "";
}
};
}
for (i = 0; i < len; i++) {
inputs[i].addEventListener("blur", makeBlurHandler());
}
.errorMessage {
color: red;
}
<p>
<label for="userName">User Name:</label>
<input type="text" id="userName">
<span class="errorMessage"></span>
</p>
<p>
<label for="passWord">Password:</label>
<input type="text" id="passWord">
<span class="errorMessage"></span>
</p>
it work for IE too, but this not for Firefox due to focus() is not working correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With