Chris Palmer Breuer
Chris Palmer Breuer

Reputation: 690

How to check the very next checkbox?

The issue I face is that I have identical "button-checkboxes", but once one of of them is clicked, I only want the closest checkbox check and uncheck.

<span class="button-checkbox">
    <button type="button" class="btn btn-sm btn-default btn-private">
        <i class="fa fa-square-o private"></i>
     <button>
     <input name="private" type="checkbox" class="hidden" />
</span>
<span class="button-checkbox">
    <button type="button" class="btn btn-sm btn-default btn-private">
        <i class="fa fa-square-o private"></i>
     <button>
     <input name="private" type="checkbox" class="hidden" />
</span>

The JavaScript code I currently use is:

$(document).on("click", ".btn-private", function() {

    $(this).find("i").toggleClass('fa-square-o fa-check-square-o');
    $(this).find('input:checkbox').prop("checked", true);

})

For some odd reason, $(this).find("i").toggleClass('fa-square-o fa-check-square-o'); correctly toggles the classes, but it seems that $(this).find('input:checkbox') does not get correctly selected, because if I manually assign an ID and $('#ID').prop("checked", true); it gets correctly checked.

Any ideas on how I can solve this issue and how I can uncheck the box on click as well, would be greatly appreciated!

Upvotes: 0

Views: 62

Answers (2)

Nikolay Ermakov
Nikolay Ermakov

Reputation: 5061

Use

$(document).on("click", ".btn-private", function() {
    $(this).find("i").toggleClass('fa-square-o fa-check-square-o');
    $(this).next().prop("checked", true); // here
})

Otherwise you are looking for checkbox inside button.

Upvotes: 2

Zevan
Zevan

Reputation: 10235

$(this).find('input:checkbox').prop("checked", true); is looking for the input inside the button.

Try looking at the next element after the button:

$(this).next().find('input:checkbox').prop("checked", true);

here is a working codepen: http://codepen.io/ZevanRosser/pen/wgjOQE

Upvotes: 1

Related Questions