submitting a form when a checkbox is checked submitting a form when a checkbox is checked php php

submitting a form when a checkbox is checked


Use JavaScript by adding an onChange attribute to your input tags

<input onChange="this.form.submit()" ... />


Yes, this is possible.

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">    <input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>    <input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>    <input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>    <input type="submit" name="submit" value="Search" /></form>

By adding onchange="document.getElementById('formName').submit()" to each checkbox, you'll submit any time a checkbox is changed.

If you're OK with jQuery, it's even easier (and unobtrusive):

$(document).ready(function(){    $("#formname").on("change", "input:checkbox", function(){        $("#formname").submit();    });});

For any number of checkboxes in your form, when the "change" event happens, the form is submitted. This will even work if you dynamically create more checkboxes thanks to the .on() method.


I've been messing around with this for about four hours and decided to share this with you.

You can submit a form by clicking a checkbox but the weird thing is that when checking for the submission in php, you would expect the form to be set when you either check or uncheck the checkbox. But this is not true. The form only gets set when you actually check the checkbox, if you uncheck it it won't be set. the word checked at the end of a checkbox input type will cause the checkbox to display checked, so if your field is checked it will have to reflect that like in the example below. When it gets unchecked the php updates the field state which will cause the word checked the disappear.

You HTML should look like this:

<form method='post' action='#'><input type='checkbox' name='checkbox' onChange='submit();'<?php if($page->checkbox_state == 1) { echo 'checked' }; ?>></form>

and the php:

if(isset($_POST['checkbox'])) {   // the checkbox has just been checked    // save the new state of the checkbox somewhere   $page->checkbox_state == 1;} else {   // the checkbox has just been unchecked   // if you have another form ont the page which uses than you should   // make sure that is not the one thats causing the page to handle in input   // otherwise the submission of the other form will uncheck your checkbox   // so this this line is optional:      if(!isset($_POST['submit'])) {          $page->checkbox_state == 0;      }}