如果没有提交表格,请留在同一页面

问题描述:

我有以下表格



I have the following form

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





和post.php文件。他们两个都正常工作。我只需要确保当我选中复选框时表单已提交,当我没有时,它应该保持在同一页面上。我找到了一些使用jquery和ajax的教程,但我被要求使用Javascript。任何人都可以提供帮助,谢谢你提前





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

function validate() {       
    if(document.getElementById('postTW').checked){
        document.getElementById("postForm").submit();
    }
    else{   
    }    
}

如果验证失败,则使validate函数返回false,否则返回true。试试这个:

page1.html

Make the validate function returns false if validation fails else true. Try this:
page1.html
<!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


post.php

<?php
echo "this is post.php";
?>