Search code examples
jquerycheckboxselectall

Make a function select-all jquery


I have a select-all jquery script I got from a site (I forgot the link).. Exactly, nothings wrong with the script. It works. But, I intend to rewrite it into a function. Just, I'm stucked.

Here is the ori script

    $("#selectall").click(function () {
     $('.case').attr('checked', this.checked);
});

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

Here is the function I write :

function klikAll(id){
   var header = $('#' + id);
   $('.foo_' + hid).attr('checked', header.prop('checked') );
}

function klikSub(hid){
   var heder = $('#' + hid);
   var subheder = $('.foo_' + hid);
   var subhederc = $('.foo_' + hid + ':checked');

   if(subheder.length == subhederc.length) {
      heder.attr("checked", "checked");
   } else {
      heder.removeAttr("checked");
   }
}

The problem is, the function is totally not working.. In jsfiddle, I've rewrite it http://jsfiddle.net/iamthom/aCJSY/6/. Could any body gimme a clue, in which part what I should fix? Or what's wrong in my function??


Solution

  • Please check this

    DEMO

    CODE

    <script type="text/javascript">
    function klikAll(id) {
        var header = $('#' + id);
        $('.foo_' + id).attr('checked', header.prop('checked'));
    }
    
    function klikSub(hid) {
        var heder = $('#' + hid);
        var subheder = $('.foo_' + hid);
        var subhederc = $('.foo_' + hid + ':checked');
    
        if (subheder.length == subhederc.length) {
            heder.attr("checked", "checked");
        } else {
            heder.removeAttr("checked");
        }
    }
    </script>
    

    Place your function within <script> block.