Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Blur event creates endless loop

On a web form, I have a question that the user must answer. However, the code below is problematic in that when the user clicks to remove the alert, it fires the blur event again and creates an endless loop.

$('#selPregnant').on('blur', function() {
    if ($("#selGender :selected").val() === "F") {
        if($("#selPregnant").val()===''){
            alert('If the individual is female, the pregnancy question MUST be answered.');
            $('#selPregnant').focus();
            return false;
        }
    }
});

How do I show the alert and set focus back on the question without triggering the blur again?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems to work if I set the focus afterwards, outside the JavaScript event loop.

$('#selPregnant').on('blur', function() {
    if ($("#selGender :selected").val() === "F") {
        if($("#selPregnant").val()===''){
            alert('If the individual is female, the pregnancy question MUST be answered.');
            setTimeout(() => $('#selPregnant').focus(), 0);
            return false;
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="selGender"><option value="F" selected="selected">Female</option></select>
<br>
<input type="text" id="selPregnant" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading