Carlo Ravelli
Carlo Ravelli

Reputation: 87

Jquery click affects more divs than it should

Got this piece of code for a dropdown textarea. Goal is to have div.card show/hide when the checkbox is clicked, and this works, but clicking div.card itself makes it hide itself, how could I prevent this from happening?

Jquery looks like this

$('.options .checkbox').click(function(){ 
    $('.options .card').toggleClass("hidden").toggleClass("show");
});

HTML looks like this

<label>
Label description
<strong>
    + € 0,50
</strong>
<input class="checkbox" type="checkbox">
    <div class="card hidden">
        <textarea>
        </textarea>
    </div>
</label>

Upvotes: 0

Views: 100

Answers (1)

Blender
Blender

Reputation: 298472

You can prevent the click event from bubbling up to the parent:

$('.card').click(function(e) {
    e.stopPropagation()
});

Or, you could verify that the target element is really the one you're after:

$('.options .checkbox').click(function(e) {
    if (!$(e.target).hasClass('checkbox')) return false; 

    $('.options .card').toggleClass("hidden").toggleClass("show");
});

Upvotes: 2

Related Questions