0

I have a simple form.

It POSTs to the server (node js / express), and has a checkbox with a 'true' value when checked.

<form id="demo_form" action="/submit_demo" method="POST">
  <input type="checkbox" id="demo_input" name="demo_input" value=true />
</form>

When I receive the data on the server, my values are wrapped in quotes - eg. "true".

This causes issues when submitting data to my api which strictly accepts booleans as true (no quotes).

I can easily manually remove the quotes from any data before submitting to my api BUT it gets a bit painful when dealing with a lot of fields.

Is there a simple solution to sending a boolean value from a form to a server without it being a string?

Any input much appreciated :)

ronnie burns
  • 230
  • 2
  • 4
  • 17
  • Probable copy of https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript – Shubham Tiwari Nov 22 '18 at 12:15
  • POST/GET parameters do not _have_ any “type”, the values are always send as strings. – misorude Nov 22 '18 at 12:15
  • 1
    That's not how checkboxes work. If checked, they are in the submitted data as a regular key-value pair, the key being the name. Unchecked, not at all. So, the Boolean is in the presence/absence, never in the `value`. – connexo Nov 22 '18 at 12:31

1 Answers1

1

If a form is POSTed and you did not check a checkbox, it will not be included in the payload. So on the server side it should be easy to identify if something was checked or not.

See this codepen for reference: https://codepen.io/anon/pen/KrowNJ

<form method="POST">
  <div>
    <input type="text" name="message" placeholder="Enter your message...">
  </div>
  <div>
    <input type="checkbox" id="subscribeNews" name="subscribe">
    <label for="subscribeNews">Subscribe to newsletter?</label>
  </div>
  <div>
    <button type="submit">Subscribe</button>
  </div>
</form>

Hope this helps!

chrisg86
  • 11,548
  • 2
  • 16
  • 30