Jay
Jay

Reputation: 360

Jquery checkbox affect one item not all items

I was wondering if someone can help me please, I have a series of checkboxes that when clicked change the div background, activate 2 inputs and add a tick icon. My issue is that when one check box is checked the class .TickIco shows for all and so does the .disableToggle

How can i get it so that this only affects one .checkBG at a time and not all of them?

Hopefully this JSFiddle will help explain what I mean.

https://jsfiddle.net/jayjay89/xfg96we5/

thanks

$(".checkBG").click(function () {
var checked = $(this).is(':checked');
var location = $(this).parent().parent().parent();
if (checked) {
    $(this).parent().parent().parent().addClass("activeformBlock");
    $(".tickIco").show();
    $(".disabletoggle").removeAttr("disabled");


} else {
    $(this).parent().parent().parent().removeClass("activeformBlock");
    $(".tickIco").hide();
    $(".disabletoggle").attr('disabled', 'disabled');
}

});

thanks

Upvotes: 0

Views: 25

Answers (2)

Pineda
Pineda

Reputation: 7593

Your issue lies in the way you are selecting the .tickIco and .disabletoggle elements:

$(".tickIco").show();
$(".disabletoggle").removeAttr("disabled");

These jquery calls use selectors that match all classes of .tickIco and .disabletoggle.


Dirty solution (finds elements of the parent with matching classes using .find()):

$(this).parent().parent().parent().find(".tickIco").show();
$(this).parent().parent().parent().find('.disabletoggle').removeAttr("disabled")

Better solution:

jQuery selecter takes the context of your selection as a second argument so you can:

var context = $(this).parent().parent().parent();
$(".tickIco", context).show();
$('.disabletoggle', context).removeAttr("disabled")

Upvotes: 0

Deep
Deep

Reputation: 9794

you can use the context in which the selector will be looked.

You already have the location variable which is the parent context for one of your row

$(".checkBG").click(function () {
    var checked = $(this).is(':checked');
    var location = $(this).parent().parent().parent();
    if (checked) {
        $(this,location).parent().parent().parent().addClass("activeformBlock");
        $(".tickIco",location).show();
        $(".disabletoggle",location).removeAttr("disabled");


    } else {
        $(this,location).parent().parent().parent().removeClass("activeformBlock");
        $(".tickIco",location).hide();
        $(".disabletoggle",location).attr('disabled', 'disabled');
    }
});

Upvotes: 2

Related Questions