jeudi 30 mars 2017

checkbox $.change is being triggered by itself and looping because it is being modified inside $.change

I have a group of checkboxes that when you click ONE, they should ALL be checked.

When a user clicks one checkbox, it checks all the other checkboxes starting with that class name. What I want is for the user to click a checkbox, and "$(".atpSelections").change" is triggered only once per click.

Here's the code:

        $(".atpSelections").change(function() {
            console.log("CHANGED");

            //Check ALL other checkboxes starting with that class name:
            var className = $(this).attr("class");
            className=className.replace("atpSelections ", "");
            className=className.trim();
            className=className.split("-");

            //Get current checkbox state
            var currentState = $(this).attr("checked");

            //Now loop through all other checkboxes starting 
            //with the same class name and check them:
            $("input[class*='"+className[0]+"-']").each(function(i){
                    //THIS IS TRIGGERING "$(".atpSelections").change"!!
                    if(currentState && currentState=="checked")
                    {
                        $(this).prop('checked', true);
                    }else
                    {
                        $(this).prop('checked', false);
                    }
                });
        });

The Problem

The problem is that when the user clicks one checkbox, the $(".atpSelections").change method gets triggered over and over because $(this).prop('checked', true); triggers $(".atpSelections").change again, and it just goes round and round.

So 1 click to a checkbox triggers 100s "change" events, when I only want it triggered once.

How do I alter the checkbox's state inside $(".atpSelections").change without triggering $(".atpSelections").change again?

Attempts

I tried changing $(".atpSelections").change to $(".atpSelections").click but it had the same issue. I think $(this).prop('checked', true); triggers the click event.




Aucun commentaire:

Enregistrer un commentaire