在form表单提交之前执行一些js判断

在form表单提交之前执行一些js判断

我刚开的时候,是用onsubmit属性的,如下所示:
index.php:

    <h2>用户登录h2>
    <form method="post" id="userForm" onsubmit="return isRemeber()">
        <div class="form-group">
            <label for="username">用户名:label>
            
        div>
        <div class="form-group">
            <label for="password">密码:label>
            <input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
        div>
        <div class="form-check">
            <label class="form-check-label">
                <input class="form-check-input" type="checkbox" id="remember_me"> 记住密码
            label>
        div>
        <button type="button" class="btn btn-primary btn-block">提交button>
    form>
div>

<script>
    function isRemeber() {
      //保存用户密码
        if ( document.getElementById("remember_me").checked) {
      
            setCookie("rmbUser","true",7);
            setCookie("username",document.getElementById("username").value,7);
            setCookie("password",document.getElementById("password").value,7);
        }
        else {
      
            setCookie("rmbUser","false",-1);
            setCookie("username","",-1);
            setCookie("password","",-1);
        }
        return false;//这句话很神奇!!!
    }
script>

我原本以为form表单会判断onsubmit的返回值,如果返回false,就不会提交,结果我错了,这个onsubmit函数确实会执行,但是却是在表单提交之后才执行,就算是onsubmit的值为false,form表单也照样会提交。

于是乎我只好换成用button的onclick函数来进行语句的表单的预处理和提交了。
如下所示:

	<h2>用户登录h2>
    <form method="post" id="userForm">
        <div class="form-group">
            <label for="username">用户名:label>
            
        div>
        <div class="form-group">
            <label for="password">密码:label>
            <input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
        div>
        <div class="form-check">
            <label class="form-check-label">
                <input class="form-check-input" type="checkbox" id="remember_me"> 记住密码
            label>
        div>
        <button type="button" class="btn btn-primary btn-block" onclick="isRemeber()">提交button>
    form>
    <script>
    function isRemeber() {
      //保存用户密码
        if ( document.getElementById("remember_me").checked) {
      
            setCookie("rmbUser","true",7);
            setCookie("username",document.getElementById("username").value,7);
            setCookie("password",document.getElementById("password").value,7);
        }
        else {
      
            setCookie("rmbUser","false",-1);
            setCookie("username","",-1);
            setCookie("password","",-1);
        }
        
        if(...){
      return ;}//这里可以写一句条件控制是否提交当前表单
        var userForm = document.getElementById("userForm");
        userForm.submit();
    }
script>

你可能感兴趣的:(JavaScript,HTML,前端开发,form表单的提交判断,onsubmit,onclick)