sammry
sammry

Reputation: 412

counting checkbox and showing the value

I am using the following jquery to show the selected number of checkboxes selected

$(document).ready(function(){
    $('.check:button').toggle(function(){
        $('input:checkbox').attr('checked','checked');
    var count = $("input[type=checkbox]:checked").size();
        $(this).val('uncheck all')
        $("#count").text(count+ " item(s) selected");
    },function(){
        $('input:checkbox').removeAttr('checked');
        var count = $("input[type=checkbox]:checked").size();
        $(this).val('check all');  
        $("#count").text(count+ " item(s) selected");
    })
})

here is the html

 <input type="button" class="check" value="check all" />
 <input type="checkbox" class="cb-element" /> Checkbox  1
 <input type="checkbox" class="cb-element" /> Checkbox  2
 <input type="checkbox" class="cb-element" /> Checkbox  3

 <p id="count"></p>

When i check all it shows the right numbers, like 3 items selected and when i uncheck all, then it shows o items selected.

But when I remove individual selected checkbox then the count does not show up. like if i remove one, then the count will still be 3 and not the 2.

how can i achieve this?

Upvotes: 0

Views: 1174

Answers (6)

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17566

$( "input[type=checkbox]" ).click(function(){

      $('#count').html($( "input[type=checkbox]:checked" ).length);  
});

Upvotes: 0

$("input:checkbox:checked").length;

DEMO

$("input:checkbox").change(function () {
    $('#count').text($("input:checkbox:checked").length);
});

Upvotes: 0

Sgoldy
Sgoldy

Reputation: 796

Try the :checked pseudo-class:

$("input[type=checkbox]").click(function () {
    $("#count").html($("input[type=checkbox]:checked").length);
});

Upvotes: 1

Balint Bako
Balint Bako

Reputation: 2560

This is giving you the count:

$('input:checkbox').on('change', function(){
    $('#count').html($('input:checkbox:checked').size());
});

jsFiddle

Upvotes: 0

NaYaN
NaYaN

Reputation: 1320

var count = 0;
$('input[type=checkbox]').each(function () {
      if (this.checked) {
          count++;
      }
});
alert(count);

Upvotes: 0

Janith Chinthana
Janith Chinthana

Reputation: 3844

try this code, check the api for more infomation

var countChecked = function() {
   var n = $( "input:checked" ).length;
    $( "p" ).text( n + (n === 1 ? " is" : " are") + " checked!" );
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );

Upvotes: 1

Related Questions