jQuery确保所有表单域都被填充 [英] jQuery make sure all form fields are filled

查看:107
本文介绍了jQuery确保所有表单域都被填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单,我正在进行客户端验证。
要验证,这些字段都不应留空。
这就是我如何去做的:

$ p $ function validateForm(){
$('。form (){
if($(this).val()===''){
return false
}
else {
返回true;
}
});





$ b

由于某些原因,我的函数总是返回false,即使所有字段都已填充。

解决方案

你不能从匿名函数中返回false。另外,如果它确实有效,如果第一个字段为空,则返回false,否则返回false,并完全忽略其余字段。可能有更优雅的解决方案,但你可以这样做:

  function validateForm(){
var isValid = true;
$('。form-field')。each(function(){
if($(this).val()==='')
isValid = false;
});
返回isValid;
}

另一个建议是:这需要您用该表单装饰所有表单字段类。您可能有兴趣使用不同的选择器进行过滤,例如 $('form.validated-form input [type =text]')



编辑啊,我被击败了,但我的解释仍然有效,希望有所帮助。


I have a simple form I'm making client side validation for. To validate, none of the fields should be left blank. This is how I go at it:

function validateForm() {
  $('.form-field').each(function() {
    if ( $(this).val() === '' ) {
      return false
    }
    else {
      return true;
    }
  });
}

For some reason, my function always returns false, even though all fields are filled.

解决方案

You cannot return false from within the anonymous function. In addition, if it did work, you would return false if your first field was empty, true if not, and completely ignore the rest of your fields. There may be a more elegant solution but you can do something like this:

function validateForm() {
  var isValid = true;
  $('.form-field').each(function() {
    if ( $(this).val() === '' )
        isValid = false;
  });
  return isValid;
}

Another recommendation: this requires you to decorate all of your form fields with that formfield class. You may be interested in filtering using a different selector, e.g. $('form.validated-form input[type="text"]')

EDIT Ah, I got beat to the punch, but my explanation is still valid and hopefully helpful.

这篇关于jQuery确保所有表单域都被填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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