Saturday, February 20, 2010

Solution: How to get your Browser to Post the Value of an UnChecked CheckBox

Heres a simple & easy way to get your Browser to Post the Value of an UnChecked CheckBox.

Please note that HTTP protocols does not mandate any browser to send values of any Form Input Elements when its not Selected/Checked.

Hence, A CheckBox that is not Checked will not be posted by the browser.


SOLUTION:

The technique is simple, Simply create another CheckBox with a different ID but with the same name as the original CheckBox but set the Style as Display: none and its Checked Status as ON and Value as empty.

When a User clicks on the CheckBox, have the logic to set the Value to the original CheckBox to 1 and the Hidden CheckBox to the value of Empty String.

When its unchecked, set the value of the second hidden CheckBox to the UnChecked value while remaining hidden eg Value to 0.

Lets call the Original CheckBox as Name:active, Id:none
Lets call the Hidden CheckBox as Name:active, Id:active_1


SAMPLE:

<form name="formx" id="formx" method="POST" action="foobar.jsp">

<input name="active" value="1" checked="checked" onclick=" if (document.formx.active.checked==true) { document.formx.active.value='1'; } else { document.getElementById('active_1').value = '0'; document.getElementById('active_1').checked = true; }" type="checkbox">

<input id="active_1" name="active" value="" style="display: none;" type="checkbox">

<input name="save" value="Save" type="submit">

</form>

---------------------------

Hope this helps
G

1 comment:

Andree Surya said...

That's a clever trick. Thanks for sharing!