Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Material Design Lite checkbox

I'm using a material design lite checkbox and I'm trying to check or uncheck the element using JavaScript. I tried this:

document.getElementById("checkbox-1").checked = true;

That do not work. I tried the same approach with jQuery:

$("#checkbox-1").prop('checked',true); 

That did not work either. Any help would be appreciated.

like image 860
Agustín Villalobos Avatar asked Jul 14 '15 17:07

Agustín Villalobos


3 Answers

Currently, this component in 1.0.0 has a bug where it is not exposed as a widget. This has been fixed. Currently in master and in a 1.0.1 patch in a few days, it will be available to everyone in a stable build.

This is the proper method to handle it that will work if you have a patched version:

To check the element: document.querySelector('.mdl-js-checkbox').MaterialCheckbox.check()

And to uncheck: document.querySelector('.mdl-js-checkbox').MaterialCheckbox.uncheck()

The full API can be discovered currently by looking at the Source code and viewing the properties that don't end in an underscore. If they end in an underscore, they are for internal use only and external use is not supported.

We are working on getting the JS API's documented, but that will take some more time to finish and roll out to the site.

like image 183
Garbee Avatar answered Nov 08 '22 08:11

Garbee


For those of us (everybody) that have an id or even a class on the <input type="checkbox"> element vs the parent <label>, the trick is to run the MDL method on the parent. Otherwise you get an .MaterialCheckbox is undefined error.

.parentElement.MaterialCheckbox.check();
.parentElement.MaterialCheckbox.uncheck();

So, for example:

var myCheckbox = document.getElementById('my-checkbox');
myCheckbox.parentElement.MaterialCheckbox.check();
like image 9
Ronnie Royston Avatar answered Nov 08 '22 10:11

Ronnie Royston


If you're using jQuery:

$('.mdl-js-checkbox').each(function (index, element) { 
    element.MaterialCheckbox.check();
})
like image 3
krisanalfa Avatar answered Nov 08 '22 09:11

krisanalfa