0

fetch variable from another function for loop

I want to fetch the OTP variable inside for loop from the first function to the second function to verify with other variable values.

function validate() {

    var a = document.getElementById("mobile").value;

    if (a == "" || a.length > 10 || a.length < 10) {
        document.getElementById("message").innerHTML = "Enter Valid Mobile Number";
        return false;
    }
    
    if (a.length == 10) {
        var elemB = document.getElementById("mobile").value;
        const url = 'http://samplereques/WRequest?RequestType=UI&phoneNo=' + elemB;
        {
            $.getJSON(url, function (data) {
                for (i = 0; i < data.length; i = i + 1) {
                    otp = data[i].OTP;
                    console.log(otp)
                }
            });
        }
    }
}

function otpvalidate() {
    var ot = document.getElementById("mobile").value;

    if (ot == "" || ot.length > 10 || ot.length < 10) {
        document.getElementById("otpreturn").innerHTML = "Enter Valid OTP Number";
        return false;
    }
    if (ot == otp) {
        alert("sucess");
        console.log("success");
    }
}

I want to fetch the OTP variable inside for loop from the first function to the second function to verify with other variable value.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • Where are you calling `otpvalidate` function? Notice also, that some of the used variables are not declared, you're creating a bunch of implicit globals. – Teemu Jul 08 '21 at 08:44
  • Call `otpvalidate(otp)` from within the `for` loop. Make the function return `true` or `false`, so you can then do `if(otpvalidate(otp)) { do something }` – Jeremy Thille Jul 08 '21 at 08:51
  • At the end of the day, or tomorrow, or when ever OP is responsive again, this will eventually be a dup of https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Teemu Jul 08 '21 at 08:53

0 Answers0