How to improve sending the state of a checkbox to another page

The check box can have two values: true or false. When we pass the form data to another page, the name and the status of the checkbox are sent when it is checked, otherwise nothing is sent.

If the page receiving the data knows the list of values to receive, this is enough: when it does not receive anything for a check box, it is deduced that it is not checked ...

If you want something more secure, a bit of JavaScript code has to be added.

Basic usage of a checkbox

As all form objects, checkbox has the properties value, name and id.

It has also an attribute without value: checked. This gives the default checked state to the box. But it can also be used to read its state.

<input type="checkbox" name="cb" onchange="alert(this.checked)" />

The onchange event is triggered when you check or uncheck the box. The code assigned displays in a message box, the state: checked or not.


With JavaScript, the false state may be passed with form data

So knowing how to read the state of the box, we want to transmit it to another page. To do this we assign the state, true or false, to the value attribute of the checkbox with JavaScript code associated with onchange.
And the state false is assigned to value by default.

<input type="checkbox"  value="false" onchange="if(this.checked) this.value='true'; else this.value='false';" />

We add a button to our demonstration to test the new status of the box.

<input type="button" onclick="alert(document.form2.cb.value')" />

The form is designated by Form2 and cb is the name of the checkbox.


You can use a general purpose function.

function chState(element)

This simplifies the code of the checkbox:

<input type="checkbox"  value="false" onchange="chState(this)" />  

Or a more simpler code:

<input type="checkbox"  value="false" onchange="this.value=this.checked" />  

Therefore, the state of the checkbox will be sent with other form data, whatever the box is checked or not.

See also

© 2009-2012