sdfgg45 sdfgg45 - 1 month ago 6
jQuery Question

How to add and remove classes when click on labels using jQuery?

I'm trying to make a filter, if a label is clicked on the filter i need to remove a class and add another, if i click the same button i want to remove the class andded and re-add the old class.

So far it works to change the color when clicked, but when i add the code for changing the label back to normal style, it changes back to normal style right after the first click.

The html sample code (also autogenerated using php)

<label class="btn btn-default">
<input type="checkbox" class="tagfilter" style="border:1px solid #520a76;padding:6px; display:none;" data-id="1" value="tag1" /> tag1
</label>
<label class="btn btn-default">
<input type="checkbox" class="tagfilter" style="border:1px solid #520a76;padding:6px; display:none;" data-id="2" value="tag2" /> tag2
</label>
<label class="btn btn-default">
<input type="checkbox" class="tagfilter" style="border:1px solid #520a76;padding:6px; display:none;" data-id="3" value="tag3" /> tag3
</label>


The jQuery code:

$('.tag-btn').click(function(){

if($(this).hasClass('btn-default')){
alert(1);
$(this).removeClass('btn-default').addClass('btn-shop-color');
}

if($(this).hasClass('btn-shop-color')){
alert(2);
$(this).removeClass('btn-shop-color').addClass('btn-default');
}
});

Answer

Just use the toggleClass() function provided by jQuery:

$('.tag-btn').click(function(){
    $(this).toggleClass('btn-default btn-shop-color');
});
Comments