Working on a SPA with Mithril.js (love it!), but having a problem with input checkboxes not behaving correctly when I assign an "onchange" listener to them.
var Widget = {
view: function(vnode) {
return m("div", [
m("input[type=checkbox]", {
id: "cb" + vnode.attrs.id,
checked: Boolean(vnode.attrs.state),
onchange: function(e) {
console.log(
(e.target.checked) ? "ON" : "OFF"
);
}
}),
m("span", vnode.attrs.name)
]);
}
}
The page will initially populate properly, with checkboxes in their correct state (on or off), but when clicking the checkbox... the checkbox element does not switch.
At first, I thought the onchange event was interrupting and blocking the DOM redraw. But, then found that if I removed the "checked: (true|false)" attribute the elements works as expected. Of course, this is not acceptable. The checkbox state needs to be presented according to it's current on/off state in the database.
I'm unsure if this is weirdness with Mithrils DOM redraw. Or some other strange behavior with HTML checkboxes and Javascript in general.
Here is a sample illustrating the broken behavior. https://jsfiddle.net/v1aq85kj/14/
Any ideas are appreciated!
You are missing out changing the value the checkbox binds to so checked/unchecked will never change.
something like this might help on the way
onchange: function(e) {
vnode.attrs.state = e.target.checked
}