jQuery 提交时检查输入是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5886555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:57:59  来源:igfitidea点击:

Check if input empty on submit

jqueryvalidationforms

提问by Osu

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.

出于某种原因,当我提交的表单没有填写任何必填字段(有两个)时,它会起作用,但如果其中一个被填写,则不会。

Any ideas why?

任何想法为什么?

Thanks

谢谢

osu

大须

回答by Ryan

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.

您的代码的问题在于,您只是在测试已标记为必需的第一个字段。$(".required input")只返回表单中与该选择器匹配的第一个输入。

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.

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

$("#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;
});

回答by David Fells

$("#register-form").submit(function() {
  $('.required input').each(function() {
    if ($($this).val() == '') { 
      $(this).addClass('highlight');
    }
  });

  if ($('.required input').hasClass('highlight')) {
    alert("Please fill in all the required fields (indicated by *)");
    return false;
  }
} 

Give that a shot.

试一试。

EDIT Moved the alert so users don't get their faces blown off with alert messages, good catch.

编辑移动了警报,这样用户就不会被警报消息炸掉,很好。

回答by Andri

Simple Solution !:

简单的解决方案!:

 function checkForm(){
        $("input.required").css("border","1px solid #AFAFAF");
        $("input.required[value=]").css("border-color","red");
        if($("input.required").val().length<2)return false;
        return true;
    }

回答by Edgar Villegas Alvarado

Basing on David Fell's answer, (that has an error, in my opinion) you could do this:

根据 David Fell 的回答,(在我看来,这是一个错误)你可以这样做:

$("#register-form").submit(function() {
  $('.required input').each(function() {
    if ($(this).val() == '') {           
      $(this).addClass('highlight');
    }
  });

  if ($('.required input.highlight').size() > 0) {
    alert("Please fill in all the required fields (indicated by *)");
    return false;
  }
} 

回答by Edgar Villegas Alvarado

Maybe your condition should be this:

也许你的条件应该是这样的:

if($("input.required").val() == '')... //Pay attention to the selector

Cause your selector was finding all inputs childrenof .required

因为您的选择器正在查找.required 的所有输入

回答by Mu Mind

If the

如果

$(".required input")

is matching more than one element, then

匹配多个元素,则

$(".required input").val() == ''

probably won't do what you're expecting.

可能不会做你所期望的。

回答by Stefan Kendall

You can't reference the values of all the form inputs like that.

您不能像这样引用所有表单输入的值。

var valid = true;
$('.required input').each(function(){
   if( $(this).val() == '' ){
      valid = false;
      $(this).addClass('highlight');
   }
});

The forms pluginwill do this for you, by the way.

形式的插件会为你做这个,顺便说一句。

回答by obinoob

name of the input or id in this case used id of the input

在这种情况下输入的名称或 id 使用输入的 id

HTML:

HTML:

<input type="text" id="id"... />

JQUERY:

查询:

if (!$("#id").val()) {
   do something...
}

回答by sandeep kumar

This code get all form fields with select list & checkboxetc.

此代码使用选择列表和复选框等获取所有表单字段。

var save_prms = $("form").serializeArray();
    $(save_prms).each(function( index, element ) {
        alert(element.name);
        alert(element.val);
    });