Handling Boolean Values with Checkboxes
I have been building some forms for Where To Go Scouting lately and got stuck on handling a boolean value with a checkbox. After spending way too long on the small problem, I finally figured out how to deal with that pesky checkbox.
A checkbox element in HTML has a value
attribute which will be passed to the
server no matter if the checkbox is checked or not. I wanted my checkbox to
simple send true
if checked and false
if not checked. I looked everywhere
and only saw solutions that used jQuery. After speaking with Ryan Glover of
The Meteor Chef he pointed me to the checked
attribute which solved half of my problem.
Here is the final solution:
My HTML checkbox element: <input type="checkbox" id="flag" name="flag" />
The secret to it all is in my Template.name.events()
. Instead of using the
target value
, you use the target checked
property:
flag: e.target.flag.checked
This will be true or false depending if the value of the checkbox is checked or not.
When editing a record in my application I did this also:
{% raw %}
<input type="checkbox" name="flag" id="flag" checked="{{flag}}" />
{% endraw %}
This will take the value in the database and put it into the checked
property,
thus checking or not checking the checkbox on form load.
Hope this helps everyone save a few minutes (or hours in my case)!