Reputation: 690
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
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
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