Vytautas
Vytautas

Reputation: 3539

How to use :not selector on click event?

First I tried like this:

$('.choose-car li:not(.selected)').click(function () {
    console.log('works and with selected');
    $(this).addClass('selected');
});

Then I thought a litle and and tried like this:

$('.choose-car li:not(.selected)').on('click', function () {
    console.log('works and with selected');
    $(this).addClass('selected');
});

both works with selected..

But now I thinking maybe I have to remove click event after first click or is there easier solution? Maybe I missing something?

Upvotes: 3

Views: 2366

Answers (3)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262939

Your code is adding the selected class after you register the handler. This is probably not what you want, since the handler will remain bound to the element even after it acquires the selected class.

Try delegating the event instead:

$(".choose-car").on("click", "li:not(.selected)", function() {
    $(this).addClass("selected");
});

Upvotes: 4

U.P
U.P

Reputation: 7442

if($(this).hasClass('selected')){
$(this).removeClass('selected')
}
else{
$(this).addClass('selected')
}

Upvotes: 0

Esailija
Esailija

Reputation: 140220

$( ".choose-car" ).on( "click", "li", function(){
    if( $(this).hasClass("selected") ) {
        return;
    }

     $(this).addClass('selected');
});

Upvotes: 0

Related Questions