form2js icon indicating copy to clipboard operation
form2js copied to clipboard

Get false value for checkbox

Open gregpettit opened this issue 10 years ago • 1 comments

Currently, when processing checkboxes, a value is only set in the new object if the checkbox is in fact checked. However, sometimes you need to explicitly know if a checkbox has become false after having been true. For example, you have a list of user permissions represented on the page, 5 of which are "true". Your code updates these to show as checked. The user deselects two of these and clicks "apply".

Your code hands off the form to form2js, which recognizes the 3 true checkboxes... which were already true. If you submit the new object up to a REST service to change the user's permissions, the 3 true options are merged into the existing 5 true options, and the 2 other options will also remain true.

I worked around it with this modification to form2js:

case 'checkbox':
  if (fieldNode.checked && fieldNode.value === "true") fieldNode.value === "true";
  if (!fieldNode.checked && fieldNode.value === "true") fieldNode.value === "false";
  return fieldNode.value;
  break;

It's quick and dirty--and it's not an opt-in method (sometimes the existing way WOULD be better!). More importantly: checkboxes don't inherently have a value of "true" or "false"... the default value is actually "on", and you can set a checkbox to have any value you want. The idea is that if it is checked, it holds the current value. Hence why form2js (correctly, if I'm being honest) doesn't return a value when it's not checked.

However, I think a lot of people DO treat checkboxes as booleans, and it would be nice to be able to collect false values for those.

Any chance we could see this become an option in the future? "collectAllValues = true" or something? Then an input like a checkbox can always have its value collected regardless of whether it is checked or not. The checked state becomes visual rather than functional at that point, and the developer is responsible for setting values like "true" or "false" on toggle.

gregpettit avatar Nov 03 '15 22:11 gregpettit

@gregpettit

i'm a fan of this package, as this pkg no longer activity

i make a pkg call lodash-form-collector, it can work well as form2js and solve

checkbox issue and has enhancement

https://github.com/crapthings/lodash-form-collector/

but it need lodash as dependency,

crapthings avatar Apr 20 '17 08:04 crapthings