-1

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');
    }
});
7
  • 1
    use .toggleClass() Commented Oct 20, 2016 at 8:40
  • 1
    label is meant to wrap only one form action element, not three... Commented Oct 20, 2016 at 8:42
  • stackoverflow.com/questions/14212721/… Commented Oct 20, 2016 at 8:43
  • I know, and i pasted wrong code, all the inputs have a own label element. i will update the code Commented Oct 20, 2016 at 8:43
  • You should read about if/else (if) statments Commented Oct 20, 2016 at 8:48

3 Answers 3

2

Just use the toggleClass() function provided by jQuery:

$('.tag-btn').click(function(){
    $(this).toggleClass('btn-default btn-shop-color');
});
Sign up to request clarification or add additional context in comments.

Comments

2

You need return in the first if, o.w. both if triggered

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

Comments

2

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

  $(this).toggleClass('btn-default btn-shop-color')
});
.btn-default {
  color: red
}
.btn-shop-color {
  color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="btn btn-default">qwe
</label>

  1. Use .toggleClass()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.