javascript - jquery 检查字段并确认

标签 javascript jquery

这是我的 jquery 代码片段。实际上,我会检查提交表单上的字段是否为空,然后如果用户名存在则显示确认对话框。

<script type="text/javascript">
jQuery(function(){ 

    $("#form").submit(function(){
        var isFormValid = true;
        if ($.trim($("#telephone").val()).length == 0){
            isFormValid = false;
        alert("Empty telephone!");
        }
    elseif(check_field() == 1){
            if(confirm('Delete?')){
        isFormValid = true;
    }else{
        isFormValid = false;
    }
        return isFormValid;
}); 

function check_field(){  
    var field = $('#field').val();  
    $.post("check_field.php", { field: field }, function(result){ 
        //if the result is 1  
        if(result == 1){  
            return 1;  
        }else{   
            return 0;  

        }  
    });
} 

 }); 
 </script>

最佳答案

一个典型的错误,你需要在ajax函数中进行回调,因为当函数执行完毕后,ajax post还没有进行:

function check_field(callback){  
    var field = $('#field').val();  
    $.post("check_field.php", { field: field }, function(result){ 
        //if the result is true
        callback(result == 1);
    });
} 

然后是这样的:

$("#form").submit(function(e){
    e.preventDefault() // prevent the form from submitting... yet
    var $form = $(this);
    check_field(function(result) {
        if(result && confirm('Delete?')) { 
            $form.submit(); // now submit it
         }
    });
});

欢迎来到异步编程的世界!

关于javascript - jquery 检查字段并确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13277923/

相关文章:

javascript - jquery 加载函数后 JS 崩溃

jquerysiblings() 获取 previous sibling 而不是下一个

javascript - DriveApp.searchFiles - 使用文件名的任何子字符串搜索文件

Apigee API 平台中忽略了 Javascript Date.toLocaleString()

javascript - jQuery Ajax - 失败的资源或 Uncaught Error

jquery - 如何在拖动时显示图像克隆?

jquery - 需要一个结合 val() 和 text() 的命令

javascript - 如何在两个 div 中显示动态内容,每个 div 具有确定的高度?

Javascript 正则表达式在不应该的情况下匹配逗号

javascript - 如何对需要其他模块的 Node.js 模块进行单元测试以及如何模拟全局 require 函数?