通过ID防止jQuery中的表单提交

时间:2014-06-10 05:26:39

标签: javascript jquery ajax forms validation

我正在使用jQuery Ajax函数来检查数据库中jquery更改函数中是否存在用户电子邮件。在Ajax响应中,有两种可能性,即用户电子邮件是否存在。如果存在,则显示错误消息。现在我想阻止表单提交,如果Ajax响应是错误的

    jQuery("#userEmail").change(function(){
//my code goes here
    if(result == 'False'){
       //prevent form here 
     }
    else {
  // else condition goes here
     }

     });

5 个答案:

答案 0 :(得分:1)

您可以设置一个全局变量,如

emailValidated = false

并且

jQuery("#userEmail").change(function(){
//my code goes here
  if(result == 'False'){
   emailValidated = false;
  }
  else {
  // else condition goes here
    emailValidated = true;
  }

 });

在表单提交之后检查emailValidated变量的值。

$(form).submit(function(){
  if(emailValidated) {
     this.submit();
  }
  else {
    return false;
  }
})

答案 1 :(得分:0)

使用e.preventDefault()阻止提交表单。

jQuery("#userEmail").change(function(e){
    if(result == 'False'){
      e.preventDefault();
     }
    else {
     }   
  });

答案 2 :(得分:0)

您需要使用提交事件处理程序:

jQuery("#userEmail").closest("form").submit(function(event){
    var $email = jQuery("#userEmail", this);

    //the email field is not `this`, but `$email` now.

    //your code goes here
    if(result == 'False'){
       event.preventDefault();
     }
    else {
       // else condition goes here
    }

});

如果需要,您仍可以将其他行为附加到更改事件。重要的是在提交事件上执行event.preventDefault()

答案 3 :(得分:0)

做这样的事情:

var result;

$.ajax({
  url: url,
  // Put all the other configuration here
  success: function(data){
    if(data == something) // replace something with the server response
      result = true; // Means that the user cannot submit the form
  },
});

$('#formID').submit(function(){
  if(result){
    alert('Email already exists.');
    return false;
  }
});

答案 4 :(得分:0)

  • 步骤如下:
    1. 从Jquery的输入字段中获取用户传递的电子邮件值。
    2. 将数据发送到您的PHP查询文件并获取有关jquery的“success:function(data)”函数的响应数据。
    3. 在页面上显示该数据数据..

查看以下链接以获取参考。 http://www.sitepoint.com/jquery-ajax-validation-remote-rule/

相关问题