Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript to Toggle Material Design Lite Switch

I have the following Material Design Lite switch in my HTML and is looking for some javascript help.

<label  class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
    <input type="checkbox" id="switch-1" class="mdl-switch__input" checked />
    <span class="mdl-switch__label">USEREMAIL Subscribed</span>
</label>

Upon clicking the switch, I'd like to add:

  1. Toggle functionality to update the checked to unchecked - like on and off switch, but is looking for JavaScript help here.

  2. I would like to really have values of "subscribed" and "unsubscribed" as text that is displayed next to it as shown (but hardcoded in the html). Is this feasible to change dynamically?

Thanks for your time. I did find this as a reference, but it was using CheckBox.

like image 368
user2690151 Avatar asked Apr 27 '16 23:04

user2690151


2 Answers

If you refer to the mdl's source code, you will find that the check and uncheck functions are bound with label tag.

You can specify an id to label like below:

<label id="check" class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
    <input type="checkbox" id="switch-1" class="mdl-switch__input"/>
    <span class="mdl-switch__label">Subscribed</span>
</label>
<input type="button" value="test switch" id="btn"/>

MDL natively supports on/off status switch on button click. You can also control the status by another button.

$("#btn").click(function() {
    if($('#check').is('.is-checked')) {
        $('#check')[0].MaterialSwitch.off();
    }
    else {
        $('#check')[0].MaterialSwitch.on();
    }
});

To update the switch label dynamically, the code can be put like below. Bind the input's change event on page load and update label text if the on/off status changes.

//toggle label
$('#check input').change(function(){
    if($(this).is(':checked'))
        $(this).next().text("Unsubscribed");
    else
        $(this).next().text("Subscribed");
});

Here is the jsFiddle code. The answer comes a bit late for you but I hope it still helps.

like image 89
ichbinblau Avatar answered Nov 19 '22 16:11

ichbinblau


Referring to the code in above question:

var myCheckbox = document.getElementById('switch-1');

myCheckbox.parentElement.MaterialSwitch.off();
…
myCheckbox.parentElement.MaterialSwitch.on();
like image 3
Hafsal Rh Avatar answered Nov 19 '22 15:11

Hafsal Rh