提交前jQuery检查输入不为空 [英] jQuery check inputs not empty before submit

查看:141
本文介绍了提交前jQuery检查输入不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究如何执行此操作的不同线程,并将以下脚本放在一起,但是,即使我在输入中键入内容以使其不为空时,也会弹出警报并显示表单不提交.

I've been looking at different threads about how to do this and got the following script together, however, even when I type into the inputs so they're not empty, I'm getting the alert pop up and the form doesn't submit.

任何人都可以看到我在做什么,或者是否有更简单/更有效的方式来做到这一点?

Can anyone see what I'm doing wrong or if there's a simpler / more efficient way of doing this?

谢谢

Osu

HTML:

<form action="#" method="post" class="signup-form">
    <div class="required">
        <label for="name">Name:</label>
        <input type="text" name="cm-name" id="name" value=""><br />
    </div>
    <div class="required">
        <label for="asd-asd">Email:</label>
        <input type="text" name="cm-asd" id="asd-asd" value="">
        <span class="btn"><input type="submit" name="submit" value="" id="signup"></span>
    </div>          
</form>

JS:

// Validate form fields in Sign up form 
$(".signup-form").submit(function(){
    var isFormValid = true;
    $(".signup-form .required input").each(function(){
        if ($.trim($(this).val()).length == 0){
            $(this).parent().addClass("highlight");
            isFormValid = false;
        } else {
            $(this).parent().removeClass("highlight");
        }
    });
    if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)");
    return isFormValid;
});

推荐答案

但是,感谢您的回答,我发现收到错误消息的原因是因为提交按钮没有值,即value =",所以它也在检查那个输入.为了纠正此问题,我必须确保Submit函数仅检查文本"输入类型:

Thanks for the answers, however, I found that the reason I was getting the error message was because the submit button had no value i.e. value="", so it was checking that input too. In order to rectify the problem, I had to make sure the submit function was checking only 'text' input types:

新JS:

// Validate form fields in Sign up form 
$(".signup-form").submit(function(){
    var isFormValid = true;
    $(".signup-form .required input:text").each(function(){ // Note the :text
        if ($.trim($(this).val()).length == 0){
            $(this).parent().addClass("highlight");
            isFormValid = false;
        } else {
            $(this).parent().removeClass("highlight");
        }
    });
    if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)");
    return isFormValid;
});

这篇关于提交前jQuery检查输入不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆