I've been working on implementing a tri-state checkbox based on the demo presented in this CSS-tricks article. However, I did a small change where I also set the input value through $(el).val() so 0 is indeterminated and 1 is checked:
inputs.on('click.tristate', function () {
el = $(this);
switch (el.data('checked')) {
// unchecked, going indeterminate
case -1:
el.data('checked', 0);
el.val(0)
el.prop('indeterminate', true);
break;
// indeterminate, going checked
case 0:
el.data('checked', 1);
el.val(1);
el.prop('indeterminate', false);
el.prop('checked', true);
break;
// checked, going unchecked
default:
el.data('checked', -1);
el.prop('indeterminate', false);
el.prop('checked', false);
}
});
This works as expected - when clicking it switches between states, and when you send the form, it sends indeterminate as 0 and checked as 1 (and unchecked it doesn't send at all).
Now I'm having trouble with setting the initial value. I've added this:
inputs.each(function () {
if ($(this).data('checked') === 0) {
this.indeterminate = true;
this.value = 0;
return;
}
if (this.checked) $(this).data('checked', 1);
else $(this).data('checked', -1);
});
It works visually, but if you run $('form').serialize() you see that it treats the indeterminate input as if it was unchecked (i.e., not adding it). If you click a few times, and do a full loop, it does add it. So what gives?
I've made a JSFiddle Demo to demonstrate the behavior. I tried many different ways to define the initial value, but I just can't seem to be able to make it treat the indeterminate field as something that needs to be added.
What can I do?