Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why counting wrong when i click select all checkbox

I have got a problem. I have some checkbox. I want to select them at once, but counting result is wrong. when If I use firefox, opera then ok but when i use crome,safari, IE then It gives me a wrong result. why? please help me.

http://jsfiddle.net/Taslimkhan/kdEmH/2/

some code I have set here:

    // add multiple select / deselect functionality
    $("#selectall").click(function () {
          $('.case').attr('checked', this.checked);
    });

    // if all checkbox are selected, check the selectall checkbox
    // and viceversa
    $(".case").click(function(){

        if($(".case").length == $(".case:checked").length) {
            $("#selectall").attr("checked", "checked");
        } else {
            $("#selectall").removeAttr("checked");
        }

    });
});
      $(document).ready(function () {
        $("input[type=checkbox]").each(function () {
          $(this).change(updateCount);
        });

        updateCount();

        function updateCount () {
          var count = $("input[type=checkbox]:checked").size();

          $("#count").text(count);
          $("#status").toggle(count > 0);
        };
      });
like image 775
Taslim Avatar asked Jan 15 '23 08:01

Taslim


2 Answers

First, .size() is deprecated. Use the length property instead.

Second, you probably want to restrict the checkboxes being counted to the ones with the .case class:

var count = $("input[type=checkbox].case:checked").length;

Third, the way your code is written, you should be calling updateCount() on the click event instead of the change event, and you don't need the anonymous function there:

$("input[type=checkbox]").click(updateCount);

I saved a new revision of your jsfiddle: http://jsfiddle.net/kdEmH/8/

like image 131
glomad Avatar answered Jan 16 '23 20:01

glomad


Click is the correct event to capture not change. Also why are you iteratively binding. Replace your document.ready with the following:

$(document).ready(function () {
    $("input").bind('click', function () {
      updateCount();
    });

    updateCount();

    function updateCount () {
        var count = $( "input:checked" ).length;

      $("#count").text(count);
      $("#status").toggle(count > 0);
    };
  });
like image 43
Angela Avatar answered Jan 16 '23 22:01

Angela