Infinite loop of jQuery focus() event with a <select> element

Marcio Mazzucato picture Marcio Mazzucato · Feb 23, 2013 · Viewed 7.3k times · Source

I have this HTML:

<select id="select-one">
    <option value="">Choose</option>
    <option value="1">House</option>
</select>

<select id="select-two">
    <option value="">Choose</option>
    <option value="A">Table</option>
</select>

And this Javascript with JQuery

$("#select-two").focus( function() {

    if( $("#select-one").val() == "" ) {
        alert("Fill select-one first!");
        return false;
    }

});

So i am getting a infinite loop with alerts because after call alert() Javascript puts the focus again in the same select (select-two).

Someone can help me to solve this please?

Answer

Boaz picture Boaz · Feb 23, 2013

Note: based on your comments, this assumes you must listen to the focus event.


Solution 1 - using blur() - effective but buggy in Chrome

In theory, the focus event is not cancelable, so return false or event.preventDefault() will have no effect in this case. However, in practice, you can reverse the event by using the blur() method.

For example:

$('#select-two').on('focus',function () {
    if ($("#select-one").val() == "") {
        $(this).blur();
        alert('Fill select-one first!');
        return false;
    }
});

See jsFiddle demo

This effectively prevents the field from regaining focus after the alert call and so the focus event is not repeated. The only problem is that in Chrome even though the field is not focused anymore, the dropdown remains open (see demo).


Solution 2 - using remove() and clone() - costly but cross-browser

If Chrome's behavior is problematic, you can take a more crude approach, whereby you remove() the select from the DOM, clone() it and then reinsert it into the DOM. This will effectively "reset" the select element completely, leaving it without focus as well as closed.

For example:

$(document).on('focus','#select-two',function (e) {
    if ($("#select-one").val() == "") {
        $(this).remove().clone().insertAfter('#select-one');
        alert('Fill select-one first!');
        return false;
    }
});

See jsFiddle demo

The upside of this approach is that it works well in Chrome too. The downside of this approach is that it involves manipulating the DOM for a very trivial issue.