I have the following code, which when you click a radio button it adds the class checked_radio
, when you click on another radio button it removes the class then adds the class to another radio button. That works great.
The second part is that I want to do a similar thing but add the class highlighted
to the parent li, it adds it fine but doesn't remove the class when clicking on another radio button. What am I doing wrong?
$('.gfield_radio input').click(function() {
$('.gfield_radio input').removeClass("checked_radio");
$(this).addClass("checked_radio");
$('input.checked_radio').closest('li').removeClass("highlighted");
$(this).closest('li').addClass('highlighted');
});
With these lines, you ensure that any previous .gfield input
no longer has checked_radio
and then add it to the one just clicked:
$('.gfield_radio input').removeClass("checked_radio");
$(this).addClass("checked_radio");
but then, after doing that, you use this to try to remove the old highlight:
$('input.checked_radio').closest('li').removeClass("highlighted");
Of course, by then, you've already updated which radio button has the checked_radio
class.
Just change the sequence:
$('.gfield_radio input').click(function() {
// Out with the old...
$('input.checked_radio').closest('li').removeClass("highlighted");
$('.gfield_radio input').removeClass("checked_radio");
// ...and in with the new
$(this).addClass("checked_radio")
.closest('li').addClass('highlighted');
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments