Click here to Skip to main content
15,879,348 members
Please Sign up or sign in to vote.
1.67/5 (2 votes)
See more:
I have the following form

HTML
<form id="postForm" action="post.php" method="post">


and a post.php file. Both of them are working properly. I just need to make sure that when I check the checkbox the form is submitted and when I don't, it should stay on the same page.I found a few tutorials using jquery and ajax, but I was required to use Javascript. Can anyone help, thank you in advanced

JavaScript
function validate() {       
    if(document.getElementById('postTW').checked){
        document.getElementById("postForm").submit();
    }
    else{   
    }    
}
Posted
Comments
Sergey Alexandrovich Kryukov 11-Jul-14 13:17pm    
Maybe there is a real problem here, but as you formulated it, it makes no sense: if a form is not submitted, no HTTP request happens, so you always stay on page. Having a check box to indicate "submitted" (are you really trying to do that?) looks absurd to me. Why?
—SA
Correct. Submit should happen with a button click. :)

1 solution

Make the validate function returns false if validation fails else true. Try this:
page1.html
XML
<!DOCTYPE html>
<html>
<head>
<script>
function validate() {
    var status = false;
    if(document.getElementById('postTW').checked){
        status = true;
    } else {
        alert("You forgot to check!");
    }
    return status;
}
</script>
</head>
<body>
<form id="postForm" action="post.php" method="post" onsubmit="return validate();">
<input type="checkbox" name="postTW" id="postTW" value="somevalue">Check to Submit
<input type="submit" value="Submit">
</form>
</body>
</html>

post.php
VB
<?php
echo "this is post.php";
?>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900