Riff
Riff

Reputation: 51

Jquery won't count checkbox when checked first time

I have a problem with my Jquery script, it has to count the checked boxes, but it won't count on the first time clicked, so i have check-uncheck-check again in order to count. It counts correctly only in firefox`

   $("#collapseOne input[type=checkbox]").click(function( event ) {  
    var max = 3;  
    var checkboxes = $('#collapseOne
    input[type="checkbox"]');

  checkboxes.change(function(){
      var current = checkboxes.filter(':checked').length;  $( "#col1" ).text(current);
      checkboxes.filter(':not(:checked)').prop('disabled', current >= max); });

http://jsfiddle.net/nm8T9/

Upvotes: 0

Views: 673

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388326

There is no need to have a click handler

var max = 3;
var checkboxes = $("#collapseOne input[type=checkbox]");
checkboxes.change(function(){
    var current = checkboxes.filter(':checked').length;
    $( "#col1" ).text(current) ;
    checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});

Demo: Fiddle

Look at this demo

Your click handler will result in the registering no-of-clicks - 1 change handler executions

Upvotes: 3

Nunners
Nunners

Reputation: 3047

You are registering the change event inside the click handler, this will not be automatically executed, you should assign the change event handler on DOM Ready.

jQuery : JSFiddle

var max = 3;
var checkboxes = $("#collapseOne input[type=checkbox]");
checkboxes.change(function(){
    var current = checkboxes.filter(':checked').length;
    $( "#col1" ).text(current) ;
    checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});

Upvotes: 0

Related Questions