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

守給你的承諾、 提交于 2019-12-05 18:37:22

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.

I think you need an extra event that change content select-two when the value of select-one has "" like 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>

JS

$("#select-one").change(function() {
    if ($(this).val() == "") {
        $("#select-two").val("");
    }
});

$("#select-two").focus(function() {
    if( $("#select-one option:selected").val() == "" ) {
        alert("Fill select-one first!");
        $("#select-one").focus();
        return false;
    }
});

Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!