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?
Note: based on your comments, this assumes you must listen to the focus event.
Solution 1 - using
blur()
- effective but buggy in ChromeIn theory, the
focus
event is not cancelable, soreturn false
orevent.preventDefault()
will have no effect in this case. However, in practice, you can reverse the event by using theblur()
method.For example:
See jsFiddle demo
This effectively prevents the field from regaining focus after the
alert
call and so thefocus
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()
andclone()
- costly but cross-browserIf Chrome's behavior is problematic, you can take a more crude approach, whereby you
remove()
theselect
from the DOM,clone()
it and then reinsert it into the DOM. This will effectively "reset" theselect
element completely, leaving it without focus as well as closed.For example:
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
JS
Demo