简体   繁体   English

如何防止表单在用户可用性检查过程中提交?

[英]How to prevent form to submit in user availability check process?

I have a registration form where i am checking user availability using jquery, but when user is not available form should not be submitted. 我有一个注册表单,我在其中使用jquery检查用户的可用性,但是当用户不可用时,不应提交表单。 How to prevent it to submitted in not availability case. 在不可用的情况下如何防止提交。 My code is 我的代码是

$(document).ready(function(){
    $('#email').change(function() {
        status=0;
        user=$('#email').val();
        $.ajax({
            type:"post",
            url:"verify-user.php",
            data:{'user':user},
            success:function(data){
                if(data=='1'){
                    $("#show_msg").html('<span style="color:#F00;">Not avilable</span>');
                }else if(data=='0'){  
                    $("#show_msg").html('<span style="color:#093;">Avilable</span>');
                }
            }
        });  
    });
});

Please help me. 请帮我。 Your help would be appreciated. 您的帮助将不胜感激。 Thanks in advance. 提前致谢。

The code to prevent form submission is tied to the event - in this case: 防止表单提交的代码与事件相关联-在这种情况下:

$('#email').change

You need to pass the event to your event handler function as an argument, and add 您需要将事件作为参数传递给事件处理程序函数,然后添加

event.preventDefault()

to your email change handler. 到您的电子邮件更改处理程序。 However, since you are calling your validation via Ajax, I believe you'll have to manually submit the form if your validation succeeds. 但是,由于您是通过Ajax调用验证的,因此我认为,如果验证成功,则必须手动提交表单。 Edited code below - not tested, but hopefully will lead you in the right direction. 以下经过编辑的代码-未经测试,但希望可以引导您朝正确的方向前进。

$(document).ready(function() {

    $('#email').change(function(event) {

        status=0;

        user=$('#email').val();

        // prevent default action
        event.preventDefault();

        $.ajax({

            type:"post",

            url:"verify-user.php",

            data:{'user':user},

            success:function(data){

                if(data=='1'){

                    $("#show_msg").html('<span style="color:#F00;">Not avilable</span>');

                } else if (data=='0') {  

                    $("#show_msg").html('<span style="color:#093;">Avilable</span>');

                   //submit your form if validation succeeds
                    $("#your-form-id").submit();

            }

        }

    });  

});

});

Couldn't you just use an if statement? 您不能只使用if语句吗?

var user=$('#email').val();
if (!user) {
   return;
}

$.ajax({

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

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