I need to “invert” a checkbox, i.e. submit the value if the checkbox is unchecked, and leave it empty if the checkbox is checked.
I do not want to prevent form submission!
I can think of two approaches:
- change appearance of the checkbox so that it looks checked if it actually isn’t and vice versa
- change a hidden input via JavaScript when the checkbox is clicked
What’s the best way to approach this? I would prefer a “pure” general solution, but since I need it for a project with twitter-bootstrap-3, jquery and prototypejs, I tagged the question accordingly and if there is an easy way using these frameworks, that’s great too.
This works as intended:
<form id="the_form" method="post" action="">
<input type="checkbox" id="the_checkbox" name="the_checkbox" value="foo" />
</form>
<script>
document.forms.the_form.observe('submit', function() {
document.getElementById('the_checkbox').checked = ! document.getElementById('the_checkbox').checked;
});
</script>
But you will see the checkbox status changing before the next page has loaded.
3
Answers
You can use
onsubmit
event this way:Ok so what i’ve understood is that you want to inverse the checkbox.
If it’s checked dont send value with the form.
If unchecked then send the value with the form.
I only didn’t get if you want to submit the form on checkbox click.
Make a hidden input with the same name that has the value.
When the checkbox is checked then disable the hiddenbox.
//EDIT forgot that unchecked checkboxes dont get send. fixed i think
you can dynamically add/remove elements to the form: