Search code examples
phpcheckboxfindclosest

How to check closest checkbox using jQuery


I have an foreach loop. In the foreach loop I have following code.

<div class="col-md-2">
    <img alt="" class=" center-block developerlocationselection check" style="width:35%; margin-top:10%;" src="../../css/collecting/route-select.png">

    <input id="checkBox" type="checkbox" class="developernames" name="developernames">

</div> 

I have an image and checkbox.

What i want to do is when i click the image, the closest checkbox to the image become checked.

This is my Javascript

<script>
$(document).ready(function () {
    //$(".developerlocationselection").on('click', function () {
    $(".developerlocationselection").click( function () {
        alert(2);
        $(this).closest().find('input[type=checkbox]').prop('checked', true);
    });
});
</script>

How I can check the closest checkbox on click of an image.


Solution

  • .closest Travels up the DOM tree until it finds a match for the supplied selector. You need to use next() or find() like this:

    $(this).parent().find('input[type=checkbox]').prop('checked', true);
    

    or

    $(this).next('input[type=checkbox]').prop('checked', true);
    

    or even

    $(this).next().prop('checked', true);