Get Value of Toggle Checkbox in Semantic UI

Danny picture Danny · Jul 17, 2016 · Viewed 10.9k times · Source

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?

Answer

Kjell picture Kjell · Jul 17, 2016

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.