简体   繁体   English

检查所有字段的空值

[英]Check empty value for all fields

I want If was value for all inputs go to url # ( <form action="#".... ) else do not go. 我想如果所有输入的值都是url #<form action="#".... )否则就不去了。 but in this code it work just for first field, i want it work for all fields .(i can not use from ajax call or preventDefault or window.location (Because one from field is input:file). how can fix it? 但是在这段代码中它只适用于第一个字段, 我希望它适用于所有字段 。(我不能从ajax callpreventDefaultwindow.location (因为从字段输入的是input:file)。如何解决?

See demo: http://jsfiddle.net/jGu4e/ 观看演示: http : //jsfiddle.net/jGu4e/

<form action="abc.html" method="POST" class="submit">
    <input type="text" name="name"><br>
    <input type="text" name="name"><br>
    <input type="text" name="name"><br>
    <button id="cli">Submit</button>
</form>



$('.submit').submit(function() {
    var input = $(this).closest('form').find('input[type="text"]');
  if (!$(input).val()){
    var cssObj={'border-radius':'5px',border:"none","box-shadow":"0 0 1px 1px red",outline:"none",background:"#ffc4c4"};
    $('input[type="text"]').css(cssObj);
    return false;
  };
});

Your problem is really twofold. 您的问题确实是双重的。 Firstly, your selector can/will return multiple fields. 首先,您的选择器可以/将返回多个字段。 Secondly, you need to return false from the .submit call when any one of these does not have a value. 其次,当其中任何一个都不具有值时,您需要从.submit调用返回false。

This jQuery should do the trick: 这个jQuery应该可以解决问题:

$('.submit').submit(function() {
        var input = $(this).closest('form').find('input[type="text"]');
        var result = true;
        input.each(function(){           
            if (!$(this).val()){
              var cssObj={'border-radius':'5px',border:"none","box-shadow":"0 0 1px 1px red",outline:"none",background:"#ffc4c4"};
              $(this).css(cssObj);
              result = false;
            };
        });
        return result;
    });

As demonstrated by your updated jsfiddle here: http://jsfiddle.net/T9YBu/1/ 如您在此处更新的jsfiddle所展示的: http : //jsfiddle.net/T9YBu/1/

EDIT: There are still defects in this code. 编辑:此代码中仍有缺陷。 Such as if a user does not enter a value it becomes red. 例如,如果用户未输入值,它将变为红色。 If the user subsequently fills in a value and clicks submit it stays red. 如果用户随后填写了一个值并单击“提交”,则该值将保持红色。 Easy enough to fix, but really this is why you should use a pre-tested validation plugin. 修复起来很容易,但这确实是您应该使用经过预先测试的验证插件的原因。

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

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