Amit
Amit

Reputation: 623

How to prevent a div to collapse when we click the checkbox inside that div?

I have a checkbox present inside a div. When the user clicks on the div(except the checkbox) another div is showing and hiding. This is achieved by JQuery. But my problem is when i click on the check box the div also showing the sliding effect(which i dont want). How to prevent the div from sliding when I click on the checkbox.

Upvotes: 1

Views: 918

Answers (2)

Amit
Amit

Reputation: 623

After struggling for a day finally i got the solution. I just add a argument to the event in JQuery. Then check if the event source is of "CheckBox" type then don't collapse the div, else collapse the div. My code is as follow:

    $(document).ready(function()
    {
       //The event handler for the click event of the div.
        $('.divClientList').click(function(e)
        {
            //Check if the event source is other then checkbox,
            //then collapse the div, else do nothing.
            if (e.target.type != "checkbox")
            {
                //If the target div content is empty then do nothing.                    
                if ($('.divContent').is(':empty'))
                {
                }
                else
                {
                    $('.divContent').slideToggle('slow');
                }
            }

        });
    });

Upvotes: 0

MvanGeest
MvanGeest

Reputation: 9661

Use the .stopPropagation() method on the checkbox. If your checkbox has the ID thecheckbox, use

$("#thecheckbox").click(function(event){
  event.stopPropagation();
});

Upvotes: 3

Related Questions