Using this in jQuery to target only one instance of a selector

Viewed 301

I am trying something simple in jQuery to help me get a handle on a bigger issue - I have a series of checkboxes, each inside a div

When the page loads, if the checkbox is checked I want the closest div to change colour BUT only the closest one and not the others

<form>

    <div class="col-lg-6">

        <input type="checkbox" class="go" checked="checked"/>

    </div>

    <div class="col-lg-6">

        <input type="checkbox" class="go"/>

    </div>

</form>

jQuery:

if ($('.go').is(':checked')) {
    $(this).closest('.col-lg-6').css('background-color','red');
}

I cannot change the selectors etc nor the HTML layout - why doesn't this recognise the instanced of go and change the closest div?

In the above it doesn't do anything - if I change the jQuery to:

if ($('.go').is(':checked')) {
    $('.go').closest('.col-lg-6').css('background-color','red');
}

then it colours both div's which I don't want

2 Answers

You need to use each to determine which this will be colored parent.

For example:

$('.go:checked').each(function(index, value){
 $(this).closest('.col-lg-6').css('background-color','red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>

    <div class="col-lg-6">

        <input type="checkbox" class="go" checked="checked"/>

    </div>

    <div class="col-lg-6">

        <input type="checkbox" class="go"/>

    </div>

</form>

If theirs no condition or any other execute code you can direct do this by:

$('.go:checked').closest('.col-lg-6').css('background-color','red');

To check a group of input check or any input, you can use Jquery:


$('input[id='value']:checked').each(

function(index,element){

//Your changes

}


);

This code will iterate the checked input checkbox and you can add any code you need

Related