Toggle classes with radio button in jQuery
- by dardub
I have a set of radio buttons where when I click a radio button, I want the label to change color or whatever. But when I click another radio button, the color goes away. Therefore I have something like this:
jQuery('label').mouseup(function(){
jQuery(this).prev().attr('checked', 'checked');
jQuery('input').next().removeClass('selected');
jQuery('input:checked').next().addClass('selected');
});
if you need to see some html:
<input type="radio" id="radio1" name="myRadio" value="option-1" />
<label for="radio1">Swing Gate</label>
<input type="radio" id="radio2" name="myRadio" value="option-2" />
<label for="radio2">Swing Gate</label>
This first removes 'selected' class from all the labels and then re-applies to only the checked labels.
It works and is simple, but I was thinking this might not be the most efficient way of doing this. I imagine that javascript is iterating through each input element and using more resources than necessary.
I'm curious if anyone knows of a common way of doing this more efficiently. I seem to be doing this type of thing quite often in my jQuery code. I've just been using jQuery for the past 3 months or so btw.