Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onblur onfocus infinite loop issue in chrome

A javascript function is used to validate the number is called in OnBlur event. if the value is not valid it will alert a pop up and return the focus to the field.

The sample code:

<!DOCTYPE html>
<html>
<body>

Enter your number: <input type="text" id="fname" onfocus="this.select()" onblur="myFunction(this)">

<script>
function myFunction(field) {
    if( isNaN(field.value)){
    alert('wrong !!!');
    field.focus();
    return false;
    }
}
</script>

</body>
</html>

validation works fine in Internet Explorer 11(version 11.447.14393.0)/ Windows 10.

But in chrome after clicking ok or close button of alert, the focus does not return to field. Again the alert pop up. so Alert is keep poping up infinitely for every OK/Close click.

the chrome version is 63.0.3239.132

like image 706
Siva Sankaran Avatar asked Mar 08 '23 00:03

Siva Sankaran


1 Answers

This looks like a chrome bug. Maybe you can file/upvote it at crbug.com.

Your need can be achieved with some workarounds.

  1. Setting the field value to empty value.

function myFunction(field)
{
    if(isNaN(field.value))
    {
        alert('wrong !!!');
        field.value="";
        field.focus();
        return false;
    }
}
Enter your number: <input type="text" id="fname1" onfocus="this.select()" onblur="myFunction(this)">
  1. In case, you don't need to clear the value, focus the element in a setTimeout.

function myFunction(field)
{
    if(isNaN(field.value))
    {
        alert('wrong !!!');
        setTimeout(function(){
            field.focus();
        },0);
        return false;
    }
}
Enter your number: <input type="text" id="fname1" onfocus="this.select()" onblur="myFunction(this)">
  1. Removing and adding the onblur event after alert finishes.

function myFunction(field)
{
    if(isNaN(field.value))
    {
        alert('wrong !!!');
        var onblurevent=field.onblur;
        field.onblur = "";
        setTimeout(function(){
            field.focus();
            field.onblur=onblurevent;
        },0);
        return false;
    }
}
Enter your number: <input type="text" id="fname1" onfocus="this.select()" onblur="myFunction(this)">
like image 69
Vignesh Raja Avatar answered Mar 19 '23 06:03

Vignesh Raja