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?

>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" />

Leave a Reply