durisvk durisvk - 24 days ago 11x
Javascript Question

Material design checkbox change doesn't work

I am trying to dynamically set the checkbox state checked to false/true.
What I have so far is this:

for(var i = 0; i < bookmakers.length; i++) {
$('#' + bookmakers[i].id + '-checkbox').prop('checked', filters['bookmakers'][bookmakers[i].id]).change();
console.log($('#' + bookmakers[i].id + '-checkbox'));

When I get log from the console, some of the checkboxes are checked: true and some checked: false. The problem is that visually I see all the checkboxes checked. We are using material design, here is some example of the checkbox creation:

for(var i = 0; i < bookmakers.length; i++) {
$bookmakers.append('<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect"><input id="' + bookmakers[i].id + '-checkbox" type="checkbox" class="mdl-switch__input" checked><span class="mdl-switch__label">' + bookmakers[i].name + '</span></label>');

and then I do this:

if(typeof componentHandler != 'undefined')

to update view. Any Ideas?


There are multiple ways of solving that problem. One I've used is this:

for(var i = 0; i < bookmakers.length; i++) {
    setCheckboxValue($('#' + bookmakers[i].id + '-checkbox'), filters['bookmakers'][bookmakers[i].id]);

and then setCheckboxValue function looks like this:

function setCheckboxValue($el, value) {
    var $parent = $el.prop('checked', value).parent();
    removeOrAddClass($parent, 'is-checked', value);

This is not the cleanest possible way to solve this problem. You can find a MaterialCheckbox object in $el.get(0) DOM Element and use it's check and uncheck methods.