I have an html form and i would like ALWAYS to have checkboxes to submit a value. How can i do that? I have one idea but i havent tried it and i am unsure if its the best way to do it (jquery to check if the box is checked or not, then set the value to 0/1 and check it off so it will submit)
To tell you the truth, this feels like a big no-no.
Anyway here goes:
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function() {
$(this).find('input[type=checkbox]').each(function () {
$(this).attr('value', $(this).is(':checked') ? '1' : '0');
$(this).attr('checked', true);
});
});
});
</script>
This goes totally against the natural/specified behaviour of checkboxes in HTML. If checked, then its value will be sent as parameter. If unchecked, then its value will not be sent as parameter. Since you already know beforehand which checkboxes are all in the HTML page, you can just apply basic math to obtain the unchecked checkboxes:
uncheckedCheckboxes = allCheckboxes - checkedCheckboxes
That's also the normal practice. If you tell a bit more about the server side language you're using to process the form, we would be able to give more tips/tricks how to achieve this the best way.
Update: if those checkboxes are created dynamically at the client side, then add for each checkbox a <input type="hidden">
field containing information about the checkbox, so that the server side knows which checkboxes are all present.
There is a legitimate reason for asking for something like this, although the behaviour envisioned here is not the right way to go about it. There is a problem with the checkbox when used correctly when editing existing data and that's that there is no way to determine whether no value was submitted because the field was not present on the form or because the user cleared all of the values. You can run into this sort of problem any time you include fields conditionally.
One could go to the trouble of maintaining a "view state", of course, but it's much easier to include a hidden "companion field" whenever a checkbox or select with the multiple option (which is also excluded when all selections are cleared) is displayed. The field should have a related but different name (a name from which the actual field name can be extracted). The Lotus Domino server has used fields named %%Surrogate_FieldNameHere for this purpose since (I believe) version 7 for exactly the reason I described here.