gables20
gables20

Reputation: 496

Increment counter ONLY once per item click

The code below basically increments a counter whenever an item with single class is clicked. There are many items with single class. What I need to do which I cannot figure out is how to make the counter increment once even though a single item has been clicked multiple times.

var counter = parseInt($.trim($(".counter").html())); 
items.click(function(){
    if($(this).hasClass("single")) { 
        $(this).addClass("selected");
        //increment counter            
        $(".counter").html(++counter);

        //if ($(this).hasClass("selected")) {               
        //    $(".counter").html(counter);
        // }
    }
    else { 
        return false;
    }

    return false;
});

Upvotes: 1

Views: 972

Answers (2)

Gavin42
Gavin42

Reputation: 490

If you can remove the class single from your code after you increment your counter, that should fix the problem.

But, you might need that class for other things, so here's another simple way we could handle it:

var counter = parseInt($.trim($(".counter").html())); 
items.click(function(){
    if($(this).hasClass("single") && !($(this).hasClass("selected"))) { 
        $(this).addClass("selected");
        //increment counter            
        $(".counter").html(++counter);
    }
});

Lastly, are you using jQuery UI Selectable? If so, the selected class could be conflicting with automatically generated code.

Upvotes: 1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Try this way to click only once

$('#first_name').one('click', function()
{
console.log('a')
});

Upvotes: 0

Related Questions