Search code examples
javascriptjqueryhtmltwitter-bootstrap-3prototypejs

Invert checkbox on submit: Set HTML form value only if checkbox is unchecked


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:

  1. change appearance of the checkbox so that it looks checked if it actually isn't and vice versa
  2. 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 , and , 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.


Solution

  • 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.

    <input type='hidden' id='hiddenCheckboxValue' value='something' name='testbox'>
    <input type='checkbox' value='' name='testbox'>
    
    
    $('#my_checkbox').click(function(){
        if($(this).is(':checked')){
            document.getElementById('hiddenCheckboxValue').disabled = true;
        } else {
           document.getElementById('hiddenCheckboxValue').disabled = false;
        }
        //If you want to submit on checkbox click
        $( "#form" ).submit();
    
    });
    

    //EDIT forgot that unchecked checkboxes dont get send. fixed i think