A control in a HTML form only gets submitted to the server if it is “successful’. For checkboxes this means that it is checked. An unchecked checkbox doesn’t get submitted. This means that in Sinatra the value of params[:the_checkbox]
is either the value of the checkbox specified in the HTML (if you don’t specify a value this will be the default which is the string 'on'
) if it is checked, or will be nil
since nothing will have been submitted.
The obvious solution is to explicitly check for nil
, and then assume that the checkbox is unchecked in that case:
checkbox_value = params[:the_checkbox].nil? ? false : true
Another option is to make use of the fact that the name/value pairs of the form data are sent to the server in the order that they appear in the document, and that when Sinatra sees a repeated name when parsing the data it will override the earlier value with the later one. This means that you can do something like this in the HTML:
<input type='hidden' name='the_checkbox' value='false' />
<input type='checkbox' name='the_checkbox' value='true' />
Now if the checkbox isn’t checked it won’t get submitted, but the hidden input will, and if it is checked it will get submitted, but will appear after the hidden input with the same name. The result is that params[:the_checkbox]
will be the string 'true'
if it has been checked, and the string 'false'
if it hasn’t. (Note that you may still have to convert the strings to booleans, depending on what you’re doing with the submitted data).