简体   繁体   English

如果字段为空,jquery会阻止表单提交?

[英]jquery prevent form from submitting if fields are empty?

I am using the following code to try and change the border colour of my input boxes and prevent the form submitting if the fields are empty. 我使用以下代码尝试更改输入框的边框颜色,并阻止表单提交如果字段为空。

Whilst this changes the border colours, the form still submits, can someone please show me where I am going wrong here, thanks in advance 虽然这改变了边框颜色,表格仍然提交,有人可以告诉我我在哪里出错了,在此先感谢

<div class="home_column">
    <div class="login_form">
        <form name="login" id="login" action="include/validate_login.php" method="post" onsubmit="return validateForm()"> 
            <h21>Username</h21><br/>
            <input type="text" class="login_form_front" id="myusername" name="myusername"><br/>

            <h21>Password</h21><br/>
            <input type="password" class="login_form_front" autocomplete="off"  id="mypassword" name="mypassword"><br/>

            <input type="submit" class="buttons_login" value="Login" id="login" name="login">
        </form> 
    </div>
</div>
function validateForm() {
    var a = document.forms["login"]["myusername"].value;
    var b = document.forms["login"]["mypassword"].value;
    if (a == null || a == "" || b == null || b == "") {
        if (a == null || a == "") { 
            document.forms["login"]["myusername"].style.borderColor = "#963634"; 
        }
        if (b == null || b == "") { 
            document.forms["login"]["mypassword"].style.borderColor = "#963634"; 
        }

        $(".form_error").show();
        $('html,body').animate({
            scrollTop: $(".form_error").offset().top - 180 
        });

        return false;
    }
}

there is an error on this line: 这一行有错误:

scrollTop: $(".form_error").offset().top - 180 

Uncaught TypeError: Cannot read property 'top' of undefined 未捕获的TypeError:无法读取未定义的属性“top”
and that's because the form_error does not exist on the html code you provided. 那是因为你提供的html代码中不存在form_error。

which make the code break and through an error before the return false line. 这会使代码在return false行之前中断并通过错误。
Everything else is ok 其他一切都还可以

Pass the event object to event handler and use event.preventDefault instead of return false; 将事件对象传递给事件处理程序并使用event.preventDefault而不是return false;

onsubmit="validateForm(event);"> 

function validateForm(event) {
  // your code
   if(conditionToStopSubmit) 
       event.preventDefault();
}

You have an odd mix of jQuery and plain JS code. 你有一个奇怪的混合jQuery和普通的JS代码。 Try this, attaching the event to the form submission in jQuery and using preventDefault to stop the request being made if the inputs are empty: 试试这个,将事件附加到jQuery中的表单提交,并使用preventDefault在输入为空时停止发出请求:

<form name="login" id="login" action="include/validate_login.php" method="post">
    <!-- your HTML -->
</form> 
$('#login').submit(function(e) {
    var formValid = true;
    var $username = $('#myusername');
    var $password = $('#mypassword');

    if ($username.val() == '') {
       formValid = false;
       $username.css('border-color', '#963634');
    }
    if ($password.val() == '') {
       formValid = false;
       $password.css('border-color', '#963634');
    }

    if (!formValid) {
        e.preventDefault();
        $(".form_error").show();
        $(document).animate({
            scrollTop: $(".form_error").offset().top - 180 
        });
    }
});

try add required in input text 尝试在输入文本中添加所需

example

<input type="text" class="login_form_front" id="myusername" name="myusername" required>

Since you're using jQuery, why not do everything in jQuery? 既然你正在使用jQuery,为什么不在jQuery中做所有事情呢? Check out my dirty version below: 看看我下面的脏版本:

(function($) {

  $("#login").on("submit", validate);

  function validate(e) {
    var $form = $("#login"),
        $uname = $form.find("input[name='myusername']"), // or $form.find("input.login_form_front") or $form.find("#myusername")
        $pwd   = $form.find("input[name='mypassword']"),
        unameVal = $.trim($uname.val()) || "", // default ""
        pwdVal = $pwd.val() || "", // no trimming as pwd could be spaces
        isValid = true;
    if (!unameVal) {
        $uname.css({ borderColor: 'red' });
        isValid = false;
    }
    if (!pwdVal.length) {
        $pwd.css({ borderColor: 'red' });
         isValid = false;
    }
    if (!isValid) {
        e.preventDefault();
    }
  }
}(jQuery));

Live demo: Validate form submit 现场演示: 验证表单提交

 <div class="home_column"> <div class="login_form"> <form name="login" id="login" action="include/validate_login.php" method="post" onsubmit="return validateForm()"> <h21>Username</h21><br/> <input type="text" class="login_form_front" id="myusername" name="myusername" required><br/> <h21>Password</h21><br/> <input type="password" class="login_form_front" autocomplete="off" id="mypassword" name="mypassword" required> <br/> <input type="submit" class="buttons_login" value="Login" id="login" name="login"> </form> </div> </div> 

try this code, And make sure that your browser is up to date. 尝试此代码,并确保您的浏览器是最新的。

Here I have just added a keyword "required" that is enough. 在这里,我刚刚添加了一个足够的关键字“required”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM