Reputation: 5069
I have this issue with jquery events binding for a select
element. When I click on the select, the .focus
class is supposed to be added. But selecting an option from the dropdown breaks the logic.
==> JSFIDDLE
Steps:
.focus
not addedCODE:
<a>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
</a>
$('select').focusin(function(){
$(this).parent('a').addClass('focus');
});
$('select').bind('focusout change',function(){
$(this).parent('a').removeClass('focus');
});
Upvotes: 0
Views: 9433
Reputation: 1086
The root of the problem is that you're only adding the class when the select is focused, and then removing it when the select value changes. The reason why the class never gets added back is because the select never loses focus when you choose one of its options. Something like this should get you the behavior you're after:
$('select').click(function(){
$(this).parent('a').toggleClass('focus');
});
$('select').blur(function() {
$(this).parent('a').removeClass('focus');
});
Edit - I'm guessing that you want to keep the functionality of removing the class when an option is selected, which is why I'd bind to click instead of focus and blur.
Upvotes: 2
Reputation: 29549
I believe you're looking for something like this, but I could be wrong:
$('select').on("focus", function(){
$(this).parent('a').addClass('focus');
});
$('select').on('blur',function(){
$(this).parent('a').removeClass('focus');
});
Use on
to bind events and use the focus
and blur
events for your select box. If I understood the question correctly this should take care of your issue.
Upvotes: 0
Reputation: 55750
That is because selecting the option removes the focus from the select
element just as you select an option from the select
So a focusout
on the select is happening here .. So this obviously removes the class on the parent element of the select
..
Also the class is not added because the select
here is already focused..
So instead use .blur() and .focus() events..
Upvotes: 0