Make sure to update the parent().siblings('label')
, rather than .siblings('label')
because the element you are binding the click event to is $(this)
, which is actually $('#front_set')
(your input) and it is a child of <label>
, not a sibling. Therefore, you need to move up a level using .parent()
:
$(document).ready(function() {
$('#front_set').click(function() {
if ($(this).is(':checked')) {
$(this).parent().siblings('label').html('checked');
} else {
$(this).parent().siblings('label').html('not checked');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="front_set">checked</label>
<label class="switch-original right">
<input type="checkbox" id="front_set">
<span class="check"></span>
</label>
I'm curious about the purpose of
<span class="check"></span>
in your code. It seems unnecessary and can be removed without affecting the functionality.
Enhanced version:
A more reliable approach would be to bind events on change
instead of click
, as checkboxes might change their value without being clicked. Here is an improved version that should work seamlessly across different devices and browsers:
$(document).on('ready', function() {
$.fn.extend({
setLabel: function() {
var label = $('[for="'+$(this).attr('id')+'"]').eq(0);
$(label).text(($(this).is(':checked') ? '' : 'not ') + 'checked');
}
});
$('#front_set').on('change', function(){
$(this).setLabel();
})
$('#front_set').setLabel();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="front_set">checked</label>
<label class="switch-original right">
<input type="checkbox" id="front_set">
</label>
This implementation also defines the label check as a jQuery function, allowing you to call it on any element using .setLabel()
. I have utilized GolezTrol's solution for selecting the label, providing more flexibility as it removes the parent/child dependency between the input and the label.