2

I am using a plugin that only triggers on click of checkbox , I need All button checkbox to existing code. I have made it so that on click of ALL CHECKBOX I manually TRIGGER click selecting all checkbox and firing the existing jquery code The problem comes when user clicks on one of checkbox I want that option to be as selected option so if all checkbox are checked (including the All) and user clicks on 3rd checkbox it should automatically select 3rd checkbox trigger click on all others (making them unchecked) including all

but my own conflicts i.e. my trigger clicks doesn't lets this happen and code gets into loop between All checkbox checked clicks and single checkbox click

I have created JS Fiddle.

In short I need toggle from checkbox button as well if all are selected on click on one of the checkbox it should make that one selected and rest all unselected

Here is the jQuery code

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>

    jQuery(window).ready(function() {
        //check ALl checkbox onClick
         jQuery('body').on('click', '.chktaxoall,.chkcmfall',function (e) {
            if(this.checked){
                    var i = 0;
                var sList;
                 jQuery(this).closest('.togglecheck').find('input:checkbox').each(function () {
                    var sThisVal = (this.checked ? "1" : "0");
                    i++;
                    if(sThisVal==0 && i>1){
                        jQuery(this).trigger('click','bot');
                    }
                });
            }
            else{
                    jQuery(this).closest('.togglecheck').find('input:checkbox').prop('checked', this.checked);
            }
        });
    //IF ALL IS SELECTED but if a user clicks on a particular checkbox uncheck all except the one user checked

    jQuery('body').on('click', '.wrap_acf input:checkbox',function (e) {
    //if all is checked and someone unchecks a checkbox make all uncheck
        var thisParent=jQuery(this).parents('.uwpqsf_class').attr('id');
        var AllTicked =jQuery("#"+thisParent+" .chkcmfall").prop('checked');
        if(thisParent && AllTicked){
            jQuery("#"+thisParent+" .chkcmfall").prop('checked',false)
            //jQuery(this).trigger('click');
        }

    })


    });

</script>

Here is the HTML structure

    <div id="mycategory" class="filter_acc_class uwpqsf_class togglecheck">
    <h2 class="LabelPlaceHolder">Category</h2>

        <!-- Add controlall and data-boxid -->
        <label class="searchLabel control controlAll checkbox" data-boxid="wrap_id_cats"><input type="checkbox" class="chkcmfall" value="" name="mycatname[]" data-boxid="wrap_id_cats"><span class="control-indicator"></span>All</label>
        <div id="wrap_id_cats" class="wrap_acf togglecheck">
                <label class="searchLabel control checkbox"><input type="checkbox" value="16" name="mycatname[]"><span class="control-indicator"></span>Bakery<span class="fltr_num">(12)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="18" name="mycatname[]"><span class="control-indicator"></span>Indulgences<span class="fltr_num">(12)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="17" name="mycatname[]"><span class="control-indicator"></span>Dairy<span class="fltr_num">(7)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="19" name="mycatname[]"><span class="control-indicator"></span>Meat<span class="fltr_num">(7)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="27" name="mycatname[]"><span class="control-indicator"></span>test4<span class="fltr_num">(7)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="24" name="mycatname[]"><span class="control-indicator"></span>test1<span class="fltr_num">(5)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="26" name="mycatname[]"><span class="control-indicator"></span>test3<span class="fltr_num">(5)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="25" name="mycatname[]"><span class="control-indicator"></span>test2<span class="fltr_num">(1)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="29" name="mycatname[]"><span class="control-indicator"></span>test6<span class="fltr_num">(1)</span></label><br>
                <label class="searchLabel control checkbox"><input type="checkbox" value="30" name="mycatname[]"><span class="control-indicator"></span>test7<span class="fltr_num">(1)</span></label>
            </div>
    </div>
user930026
  • 1,647
  • 5
  • 34
  • 59
  • First of all, you can use `$` instead of `jquery` in your code. For example: `$(window).ready(function () {...`See this for more details: http://stackoverflow.com/a/1150402/2199064 – MattD Aug 19 '14 at 13:24
  • I want this to work with trigger and if all are checked http://goo.gl/mQDPF4 and you click on BAKERY it should just leave bakery selected – user930026 Aug 19 '14 at 13:39
  • Yeah, I get that. I'm telling you that you don't need to write `jquery` every time you want to invoke the jquery function. You can simply type `$`. – MattD Aug 19 '14 at 13:40

3 Answers3

3

Not sure I completely understand what you're asking, but with this script you can check/uncheck with one checkbox which reacts to changes of other checkboxes as well.

JavaScript:

$("input[type=checkbox]:not(.chkcmfall)").on("change", function () {
    if ($(".chkcmfall").is(":checked")) {
        $("input[type=checkbox]:not(this)").prop("checked", false);
        $(this).prop("checked", true);
    }

    $(".chkcmfall").prop("checked", $("input[type=checkbox]:not(.chkcmfall):checked").length == $("input[type=checkbox]:not(.chkcmfall)").length);
});

$(".chkcmfall").on("change", function () {
    $("input[type=checkbox]").prop("checked", $(this).is(":checked"));
});

What does it do? It applies an eventhandler to all checkboxes except the one with class chkcmfall. Whenever one of these checkboxes change from checked to unchecked or vice versa, it counts all checked checkboxes (except the one with class chkcmfall) and if it matches the total amount of checkboxes, it checks the chkcmfall-checkbox as well. Otherwise it unchecks it.

When the chkcmfall-checkbox is checked, all other checkboxes are also checked.

EDIT: When the chkcmfall-checkbox is checked and then another checkbox is checked, only this latter one will be checked and the rest will be unchecked.

EDIT 2: Check all box now acts as a check/uncheck all box.

FIDDLE


EDIT 3: Added a new solution not to be using the prop attribute, but by using the click event of checkboxes as per request of the OP. I've made a difference between a click from a user and a click triggered by code by passing in an extra parameter in the trigger-function. This will prevent the infinite loops the OP was talking about, since we can now prevent the execution of triggering click events based on the source of the click.

JavaScript:

jQuery(window).ready(function () {
    //check ALl checkbox onClick
    jQuery('body').on('click', '.chktaxoall,.chkcmfall', function (e, source) {
        var all = $(this).is(":checked");
        if (source != "code") {
            $("input[type=checkbox]:not(this)").each(function () {
                if ($(this).is(":checked") != all) 
                    $(this).trigger("click", "code");
            });
        }
    });

    jQuery('body').on('click', '.wrap_acf input:checkbox', function (e, source) {
        var allChecked = $(".chkcmfall").is(":checked");
        if (source != "code" && allChecked) {
            $(".wrap_acf input:checkbox:not(this)").trigger("click", "code");
            $(".chkcmfall").trigger("click", "code");
        } else if (source != "code") {
            if ($(".wrap_acf input:checkbox:checked").length == $(".wrap_acf input:checkbox").length) 
                $(".chkcmfall").trigger("click", "code");
        }
    })
});

NEW FIDDLE


Edit 4: Updated the answer to reflect the wishes of OP to be able to have multiple sets of checkboxes.

For this approach to work you have to be able to set data--attributes to both the checkboxes and the (un)select-all-checkbox. In the following example, the script only applies the checking/unchecking of checkboxes based on a data-attribute called set.

$(document).ready(function () {
    //check ALl checkbox onClick
    $("body").on("click", ".chktaxoall,.chkcmfall", function (e, source) {
        var all = $(this).is(":checked");
        var set = $(this).data("set");

        if (source != "code") {
            $("input[type=checkbox][data-set='" + set + "']:not(this)").each(function () {
                if ($(this).is(":checked") != all) 
                    $(this).trigger("click", "code");
            });
        }
    });

    $("body").on("click", ".wrap_acf input:checkbox", function (e, source) {
        var set = $(this).data("set");
        var allChecked = $(".chkcmfall[data-set='" + set + "']").is(":checked");

        if (source != "code" && allChecked) {
            $(".wrap_acf input[type=checkbox][data-set='" + set + "']:not(this)").trigger("click", "code");
            $(".chkcmfall[data-set='" + set + "']").trigger("click", "code");
        }
        else if (source != "code")
        {
            if ($(".wrap_acf input[type=checkbox][data-set='" + set + "']:checked").length == $(".wrap_acf input[type=checkbox][data-set='" + set + "']").length)
                $(".chkcmfall[data-set='" + set + "']").trigger("click", "code");
        }
    })
});

FIDDLE 3

ZiNNED
  • 2,620
  • 20
  • 31
  • Read his comment on the other post. This is very close to what he's looking for, but not quite. – MattD Aug 19 '14 at 13:35
  • @MattD Saw it. Changed the code to reflect the wishes. – ZiNNED Aug 19 '14 at 13:48
  • this is very close to what I need i tried editing your code but wasnt successfull , can you make it so that clicking on all if all are checked should uncheck rest too so all button can check and uncheck (both) – user930026 Aug 19 '14 at 13:55
  • @user930026 The check all box should now work as uncheck all as well. – ZiNNED Aug 19 '14 at 14:09
  • i have given you +1 and right answer as it does what is needed but as my question said I needed to to work with TRIGGER('click') rather than prop as I am using an existing jquery plugin which only works on click on checkbox not prop property If you can gimme hint about this I will hugely appreciate your time and efforts into this I tried to make it work but my code gets into infinite loop – user930026 Aug 19 '14 at 14:20
  • 1
    @user930026 I've updated the answer with a solution which uses `trigger` events instead of updating `props`. Also a new fiddle is added to demonstrate the code. Hopefully you can work with this, because I'm running out of ideas of how to achieve what you want :) – ZiNNED Aug 19 '14 at 14:55
  • Thank you thats exactly what I needed I tried alot using the trigger and passing variable as you did (ps named it code too) But wasnt able to do it, your code is best example of How to handle On click checkbox with trigger function . really grateful for your help, I know this would have been time consuming , thanks for sparing for your time to help me out on this – user930026 Aug 19 '14 at 15:03
  • thank you for your help again I stumbled upon again as I have multiple boxes of categories so each need to have separate All checkbox I have been trying to ammend your code to produce result (( http://jsfiddle.net/Lhdaa53w/ )) – user930026 Aug 19 '14 at 18:31
  • 1
    @user930026 I've updated the answer and added a new fiddle. For this to work you have to be able to set `data-` attributes to the checkboxes involved. See the fiddle for more information. Hope this helps! – ZiNNED Aug 19 '14 at 20:31
0

supposing you have a table with un checkbox (A) (with class: checkall) as part of a header. then all elements in this column are CHECKBOXES (B) (with class: checkitem ) then you want to change the state of all checkboxes (B) (the checked will be unchecked and vice-versa):

$(".checkall").click(function() {
    var value = $(this).is(':checked');
    $('.checkitem:checkbox').each(function(){this.checked = !this.checked;})      
});

Rastalamm
  • 1,712
  • 3
  • 23
  • 32
-1

I'm not sure I follow, but here's a simple script to uncheck all checkboxes after a checkbox has been checked:

EDIT: realized you're looking to check/uncheck with one specific checkbox.

$('.chkcmfall').click(function(){
    var chall = this;
    $('input:checkbox').attr('checked',$(chall).attr('checked');
});

EDIT 2: accounting for your comment:

$('input:checkbox').click(function(){
    var clicked_box = this

    // see if all checkboxes are checked
    if($('input:checked').length == $('input:checkbox').length){
        $('input:checkbox').attr('checked','false');
        $(clicked_box).attr('checked'),'true');
    }
});
Travis Heeter
  • 13,002
  • 13
  • 87
  • 129
  • I already have check all/uncheck all working I seek Suppose all checkbox are checked INCLUDING the ALL checkbox If now I click on one of the checkbox other than ALL. It should unselect all except the one that has been clicked – user930026 Aug 19 '14 at 13:33
  • Maybe you should be using radio buttons instead! Then you wouldn't even need JavaScript. – Michael Aug 19 '14 at 13:50
  • You got a type in your code in the line `$(clicked_box).attr('checked'),'true');` - it misses a bracket. And probably it should be `$(clicked_box).prop('checked',false);`, have you tested your code, I doubt it works at all?... – Anubioz Apr 05 '18 at 11:48