Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Value of Toggle Checkbox in Semantic UI

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?

like image 228
Danny Avatar asked Jul 17 '16 20:07

Danny


2 Answers

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.

like image 177
Kjell Avatar answered Oct 03 '22 21:10

Kjell


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();
    }
});
like image 30
kntx Avatar answered Oct 03 '22 19:10

kntx