Get Value of Toggle Checkbox in Semantic UI

12,811

Solution 1

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.

Solution 2

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();
    }
});
Share:
12,811
Danny
Author by

Danny

Updated on June 30, 2022

Comments

  • Danny
    Danny almost 2 years

    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?

  • Martin Wickman
    Martin Wickman about 6 years
    This is the best answer since it uses semantic API to query the checkbox: $(...).checkbox('is checked')