Checking Javascript Checkbox

I would like to use Javascript to check if the checkbox was checked and if the checkbox is not checked, the submit form will not continue until it is checked. Below are my codes.

<SCRIPT language=javascript> function checkAcknowledgement(checkbox){ alert(checkbox.toString()); if (checkbox.checked == false){ alert('Please read through the acknowledgement and acknowledge it.'); return false; } else { return true; } } </script> <form action="ioutput.php" method="POST"> <input name="form" type="hidden" id="form" value="true"> ... some html form ... <input type="checkbox" id="acknowledgement" value="1" /><br><br> <input type="submit" value="submit" onclick="return checkAcknowledgement(this)"/> </form> 

Whenever a form is validated or not, it returns a warning that the form has not been validated, even though I manually validate it. How to fix it?

+4
source share
3 answers

You need to bind the event to the form instead of the submit button. Also, if you want the input flag to be presented, add a name instead of an ID:

 <input type="checkbox" name="acknowledgement" value="1" /><br><br> <form action="ioutput.php" method="POST" onsubmit="return checkAcknowledgement(this)"> 

Then change the function:

 function checkAcknowledgement(form){ var checkbox = form["acknowledgement"]; alert(checkbox); //shows [HTMLInputElement] if (!checkbox.checked){ //A shorter method for checkbox.checked == false alert('Please read through the acknowledgement and acknowledge it.'); return false; } else { return true; } } 
+12
source

You check if the submit button has been checked, which, of course, it will never be.

Submit the function form, not the submit button itself:

 <input type="submit" value="submit" onclick="return checkAcknowledgement(this.form)"/> 

You need a name in the field to find it:

Use the link to the form to access the check box:

 <script type="text/javascript"> function checkAcknowledgement(frm){ var checked = frm.acknowledgement.checked; if (!checked){ alert('Please read through the acknowledgement and acknowledge it.'); } return checked; } </script> 
+1
source

Since you added this function to the onclick submit button, the value of 'this' does not apply to the flag that you expect to receive in the function. You can replace 'this' with document.getElementById ("confirmation")

+1
source

All Articles