检查输入是否为空 [英] Check if input empty on submit

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

问题描述

我一直在寻找解决方案,但是似乎找不到适合我的示例.这是到目前为止我得到的:

I've been looking around for a solution to this, but can't seem to find any examples that work for me. Here's what I've got so far:

$("#register-form").submit(function(){
            if($(".required input").val() == '') {
                alert("Please fill in all the required fields (indicated by *)");
                $(".required").addClass('highlight');
                // $('input[type=submit]', this).attr('disabled', 'disabled');
                return false;
            }
        });

由于某种原因,当我提交的表单中没有填写任何必填字段(有两个)时,它就可以工作,但是如果填写其中一个,则不能.

For some reason, when I submit the form with none of the required fields filled in (there are two), then it works, but if one of them is filled out, it doesn't.

有什么想法吗?

谢谢

osu

推荐答案

您的代码存在的问题是,您仅测试了根据需要标记的第一个字段. $(".required input")仅返回表单中与该选择器匹配的第一个输入.

The problem with your code is that you're only testing the first field you've got flagged as required. $(".required input") only returns the first input in your form that matches that selector.

这将循环显示所有标记为必需的输入(根据您的选择器).如果找到一个值为''的值,则它将Submit函数设置为返回false并突出显示空白字段.还会从现在有效但以前在早期表单提交尝试中无效的字段中删除突出显示类.

This loops through all the inputs in the form that are flagged required (according to your selector). If it finds one with a value of '' then it sets the submit function to return false and highlights the blank fields. It also removes the highlight class from fields that are now valid but were previously invalid in an early form submit attempt.

$("#register-form").submit(function(){
    var isFormValid = true;

    $(".required input").each(function(){
        if ($.trim($(this).val()).length == 0){
            $(this).addClass("highlight");
            isFormValid = false;
        }
        else{
            $(this).removeClass("highlight");
        }
    });

    if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");

    return isFormValid;
});

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

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