skip to Main Content

auto Submmiting a form only when a checkbox is checked.

so i’ve been searching for something like this for awhile and didn’t found the proper answer, i’ve got a chechbox input that has 2 diffrent roles depending on whether it’s checked or unchecked. the answers that i’ve found were something like this:

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

or html:

<form method="post" id="form2">
        
  <input type="checkbox" value="on" id="switch" onchange="submit()">      
</form>

js:

function submit () {
$("#switch").change(function() {
        console.log($("#switch").val());
        $('#form2').delay(200).submit();
    });
}

as you can see this function will work whether the input gets checked or unchecked and i only want it to work when it gets checked (or only when it gets unchecked).
i can use a php trick to deactivate the onchange event temporarily but i don’t think that’s a good way to do it.
can anyone help here?
thanks

2

Answers


  1. You can write a a function which check if checkbox is checked (or unchecked) and then call submit() then instead of directly linking submit to onchange, link that function.
    Hope this helps.

    Login or Signup to reply.
  2. You were halfway there. Attaching the change event isn’t a bad idea. The problem is that both "checked" and "unchecked" are change events. Hence your function will get executed, no matter if it’s checked or unchecked.

    The solution is to check whether your checkbox is checked or unchecked inside the function that you run on the change event:

    // Make sure the DOM is loaded before executing this JS code
    document.addEventListener("DOMContentLoaded", function(ev){
    
      // Get the checkbox element
      const checkBoxSwitch = document.getElementById('switch');
    
      // Attach an event handler to the checkox
      checkBoxSwitch.addEventListener("change", function(e){
        
        // In case the checkbox is checked
        if(checkBoxSwitch.checked == true) {
          console.log("The checbkox is checked, submit form");
        }
        // In case the checkbox is not checked
        else {
          console.log("The checkbox is not checked. Do not submit form");
        }
      });
    });
    <form method="post" id="form2">
      <input type="checkbox" value="on" id="switch"> Check me to submit!
    </form>

    I’ve commented the code so you can see how it works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search