繁体   English   中英

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

[英]Prevent form submission in jQuery by ID

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

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

     });

您可以将全局变量

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;
  }
})

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

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

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

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
    }

});

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

做这样的事情:

var结果;

$.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;
  }
});
  • 步骤如下:
    1. 从Jquery的输入字段中获取用户传递的电子邮件值。
    2. 将数据发布到您的PHP查询文件,并获取有关jquery的“成功:函数(数据)”函数的响应数据。
    3. 在页面上显示该数据数据。

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

暂无
暂无

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

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