简体   繁体   中英

How to check the return of a JavaScript function in onchange event

How to call a function inside onchange if the return of previous function is true, what i am trying is calling many function on onchange event, but the last function should call if the return of previous function is true. my code is bellow:

<input type="text" name='test' id="test" onchange="remLdZero('test'); validatetest(); if(checkDuplicate('test', 'url','divid')===true){ nextfunction();};"  maxlength="10"  required>

my jvascript checkDuplicate() is below

function checkDuplicate(fieldId,page,msgArea){  
     var fieldVal= $('#'+fieldId).val();
     $.ajax({    
        type: "POST",
        url: page,
        data: fieldId+'='+fieldVal,    
        //dataType: "html",    
        success: function(data){
            if(data == 1){
                $('#'+msgArea).css("display","none");
                if(fieldId == 'test'){
                     return true;
                }
            }else{
                $('#'+msgArea).html(data);
                $('#'+msgArea).css("display","block");
            } 
       }
    }); 
 }

Note: If i call my nextfunction() instade of return true line, it works but as my nextfunction() brings a popup then browsers block the popup while if i call the nextfunction in onchange without checking the previous function it works.

Any soloution to fix it.

Here you go.

HTML

<input type="text" name='test' id="test" onchange="remLdZero('test'); validatetest(); checkDuplicate('test', 'url','divid', nextfunction);"  maxlength="10"  required>

JS

function checkDuplicate(fieldId,page,msgArea,callBakFn){  
 var fieldVal= $('#'+fieldId).val();
 $.ajax({    
    type: "POST",
    url: page,
    data: fieldId+'='+fieldVal,    
    //dataType: "html",    
    success: function(data){
        if(data == 1){
            $('#'+msgArea).css("display","none");
            if(fieldId == 'test'){
                 if(typeof callBakFn == "function"){
                     callBakFn();
                 }
            }
        }else{
            $('#'+msgArea).html(data);
            $('#'+msgArea).css("display","block");
        } 
   }
}); 
}

Now your nextFunction will only execute after your ajax request is done and ur result is true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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