jquery函数if语句

时间:2014-10-16 17:30:58

标签: javascript jquery jquery-validate

我正在使用jquery验证插件来验证我的表单。下面的函数显示检测到错误的每个字段下的错误。

errorPlacement : function(error, element) {
            error.insertAfter(element.parent());

        }
    });

如何判断是否已使用此功能“屏幕上是否显示错误”?

我正在尝试评估表单是否已经过验证,因此我可以执行其他逻辑,例如禁用提交按钮或将按钮文本更改为“请稍候”。

我不确定如何做到这一点。

任何帮助将不胜感激。 谢谢

5 个答案:

答案 0 :(得分:3)

为什么不设置一个布尔变量来表明该方法已被调用:

hasError: false,
errorPlacement : function(error, element) {
    error.insertAfter(element.parent());
    this.hasError = true
}

然后,您可以随时查看hasError。请务必将hasError存储在对象上,以免污染全局命名空间。

答案 1 :(得分:1)

您可以使用submitHandler,因为它是回调,用于在表单有效时处理实际提交。所以,

$("#your-form").validate({
     .....
     submitHandler: function(){
        //form is valid 
        //do some logic
        $('#your_submit_btn_id').attr('disabled','disabled');
     },
    .....
});

答案 2 :(得分:0)

您始终可以使用以下代码处理提交事件:

$("#myform").validate({
  submitHandler: function(form) {
    // some other code
    // maybe disabling submit button // $('#submit').attr('disabled', true);
    // then:
    $(form).submit();
  }
 });

submitHandler只有在表单获得验证后才会被调用&没有错误。

可以在此处找到文档:http://jqueryvalidation.org/documentation/

答案 3 :(得分:-1)

你可以看一下:

DEMO

/*error and element is parameter*/
errorPlacement: function(error, element) { 

  error.appendTo( element.parent("td").next("td") );

}

答案 4 :(得分:-1)

$('#myform').on('submit', function(){
    if($(this).valid()) //this returns true if the form is valid, and false if there is some validation error
    {
        //submit the form
    }
    else
    {
        //disable the submit button or change text as desired
        return false; //to avoid form submission
    }

});