Skip to content Skip to sidebar Skip to footer

Count + / - For Checkbox Click And Unclick

When a user clicks the checkbox the counter #counter +1, thats fine, but when he unchecks it does not -1 for the same checkbox. I want to +1 when they click a particular checkbox

Solution 1:

$('.CheckBox').change(function() {
  if (this.checked) {
    i++;
  } else {
    i--;
  }
  $('#Counter').html('( '+i+' Selected )');
});

Make sure you initialise var i = 0; when the page loads.

Solution 2:

try a different approach:

$('.CheckBox').change(function(){

  var n_checkboxes_checked = $('.CheckBox:checked').length;
  $('#Counter').html(n_checkboxes_checked + ' Selected');
});

Solution 3:

jsFiddle demo: http://jsfiddle.net/ENxnK/2

Use change(), not toggle()

var i = 0;
$('.CheckBox').change(function() {
    if ( $(this).attr('checked') ) {
        i++;
    } else {
        i--;
    }

    $('#Counter').html('( ' + i + ' Selected )');
});

Solution 4:

You don't have any code that deals with clicking on checkbox here. .toggle in jquery just deals with hiding/showing element.

upd. i think you don't need to go through all .checkbox elements as others have proposed.. and you don't need global variable i. Instead something like

$('.CheckBox input').click(function(){
    $('#Counter').html('( '+$('.CheckBox input:checked').length()+' Selected )');
}

Solution 5:

in the jQuery documentation it says....

    Description: Bind two or more handlers to the matched elements, to be executed on alternate clicks.

.toggle( handler(eventObject), handler(eventObject) [, handler(eventObject)] )
handler(eventObject)A functionto execute every even time the element is clicked.
handler(eventObject)A functionto execute every odd time the element is clicked.

so it has nothing to do with check/uncheck

do it this way

$('.CheckBox').click(function(){
    if($(this).attr('checked')){
        $('#Counter').html('( '+i+' Selected )');
        i++;
    }else{
        $('#Counter').html('( '+i+' Selected )');
        i--;    
    }
}

yes click instead of toggle...i missed that and u shud use attr instead

Post a Comment for "Count + / - For Checkbox Click And Unclick"