从JavaScript检查MDL复选框

时间:2016-02-15 10:24:48

标签: jquery material-design material-design-lite

以下是我尝试取消/检查MDL checkbox的代码和小提琴。在取消/检查时,它的状态/ UI /设计没有更新。尝试了this SO solution,但它没有用。

<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
    <input id="MdlCheckBox" type="checkbox" class="mdl-checkbox__input" value='0' />
    <span class="mdl-checkbox__label">Check Me</span>
</label>
<input type='button' value='check/uncheck' id='btn' />
$("#btn").click(function() {
    var chk = $("#MdlCheckBox")[0];
    chk.checked = chk.checked ? false : true;
    $(".mdl-checkbox__label").html(chk.checked ? "Check Me (Unchecked)" : "Check Me (Checked)");


    // below is SO solution tried but giving error
    var mdlComp = new MaterialCheckbox(chk);
    mdlComp.check();
});

https://jsfiddle.net/aLfqkL4q/1/

1 个答案:

答案 0 :(得分:4)

您需要定位标签,而不是输入。 See this fiddle

<label id="check" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
    <input id="MdlCheckBox" type="checkbox" class="mdl-checkbox__input" value='0' />
    <span class="mdl-checkbox__label">Check Me</span>
</label>
<input type="button" value="test check" id="btn"/>


$("#btn").click(function() {
    if($('#check').is('.is-checked')) {
    document.querySelector('#check').MaterialCheckbox.uncheck();
  }
  else {
    document.querySelector('#check').MaterialCheckbox.check();
  }
});