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
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.
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:
I’ve commented the code so you can see how it works.