Reputation: 1170
jQuery('.checkbox1').click(function(){
jQuery(this).parent().toggleClass('active')
});
jQuery('.checkbox2').click(function(){
jQuery(this).parent().toggleClass('active')
});
jQuery('.checkbox3').click(function(){
jQuery(this).parent().toggleClass('active')
});
jQuery('.checkbox4').click(function(){
jQuery(this).parent().toggleClass('active')
});
I run the same function on all 4 of them. Can i use something like .each()
? Can someone show me how to condense this code?
Thanks
Upvotes: 0
Views: 57
Reputation: 149030
You could simply do this:
jQuery('.checkbox1, .checkbox2, .checkbox3, .checkbox4').click(function(){
jQuery(this).parent().toggleClass('active')
});
Or you could create a new class, say checkbox
to apply to all of your checkboxes, then use this:
jQuery('.checkbox').click(function(){
jQuery(this).parent().toggleClass('active')
});
Upvotes: 3
Reputation: 388316
The best way could be to add an additional class checkbox to all the elements then use
<input type="checkbox" class="checkbox checkbox1" />
<input type="checkbox" class="checkbox checkbox2" />
<input type="checkbox" class="checkbox checkbox3" />
<input type="checkbox" class="checkbox checkbox4" />
then
jQuery('.checkbox').click(function(){
jQuery(this).parent().toggleClass('active')
});
if you can't do that then use multiple selector
jQuery('.checkbox1, .checkbox2, .checkbox2, .checkbox4').click(function(){
jQuery(this).parent().toggleClass('active')
});
Upvotes: 2