Home:ALL Converter>Javascript checkbox checking

Javascript checkbox checking

Ask Time:2011-10-23T22:31:10         Author:thotheolh

Json Formatter

I would like to use Javascript to check if a checkbox has been checked and if the checkbox is not check, the submission form would 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 the form is checked or not, it returns the alert warning that the form have not been checked despite me checking it manually. How should I fix it ?

Author:thotheolh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/7866722/javascript-checkbox-checking
Rob W :

You have to bind the event to the form instead of the submit button. Also, if you want the checkbox input to be submitted, attach a name instead of ID:\n\n<input type=\"checkbox\" name=\"acknowledgement\" value=\"1\" /><br><br>\n<form action=\"ioutput.php\" method=\"POST\" onsubmit=\"return checkAcknowledgement(this)\">\n\n\nThen, modify the function:\n\nfunction checkAcknowledgement(form){\n var checkbox = form[\"acknowledgement\"];\n alert(checkbox); //shows [HTMLInputElement]\n if (!checkbox.checked){ //A shorter method for checkbox.checked == false\n alert('Please read through the acknowledgement and acknowledge it.');\n return false;\n } else {\n return true;\n }\n}\n",
2011-10-23T14:33:03
Guffa :

You are checking if the submit button is checked, which it naturally never will be.\n\nSend the form to the function rather than the submit button itself:\n\n<input type=\"submit\" value=\"submit\" onclick=\"return checkAcknowledgement(this.form)\"/>\n\n\nYou need a name on the checkbox to find it:\n\n\n\nUse the form reference to access the checkbox:\n\n<script type=\"text/javascript\">\n\nfunction checkAcknowledgement(frm){\n var checked = frm.acknowledgement.checked;\n if (!checked){\n alert('Please read through the acknowledgement and acknowledge it.');\n }\n return checked;\n}\n\n</script>\n",
2011-10-23T14:36:21
yy