I have a Semantic UI toggle checkbox setup in HTML like this
<div class="ui toggle mini checkbox">
<input type="checkbox" name="myLayer">
<label>myLayer</label>
</div>
And I want to perform some action when the checkbox is either toggled or untoggled. Right now I have this written:
$('.ui.toggle').click(function() {
checked = $('.ui.toggle').is(':checked');
console.log(checked);
if (checked === true) {
myLayer.show();
}
else {
myLayer.hide();
}
});
However, the value of checked
is always false
, no matter whether the toggle is on or off! Why is this the case?
The selector '.ui.toggle'
is referencing the parent container of your input. The right selector would be '.ui.toggle input'
. Then you also should get a changing value for your variable.
Since you are already in the click handler, it would be even nicer to search for your input this way: $(this).find('input').is(':checked')
. This way jQuery does not has to parse the whole DOM tree once again to find the input child node.
It'd be better if you init your checkbox with Semantic as followed:
$('.ui.toggle').checkbox({
onChecked: function () { myLayer.show(); },
onUnchecked: function () { myLayer.hide(); }
});
Of course you can always read the value of your checkbox with .checkbox('is checked')
or .checkbox('is unchecked')
. To be able to read the value, your checkbox has to be initialized with $('.ui.toggle').checkbox()
.
For example, this code does the same thing as the segment on top of my answer:
$('.ui.toggle').checkbox();
$('.ui.toggle').click(function() {
if ($('.ui.toggle').checkbox('is checked')) {
myLayer.show();
}
else {
myLayer.hide();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With