Home > OS >  how can i get the value of variable inside function to outside the on jquery
how can i get the value of variable inside function to outside the on jquery

Time:06-19

can i take the value from 'a = entry.username' out of the function? i want to get value that already looping inside the function

$('#btnlogin').click(function(){
        var usernamelogin = $('#usernamelogin').val()
        var passwordlogin = $('#passwordlogin').val()
        var data_user1 = JSON.parse(localStorage.getItem('data_user'))
        
        for(var i in data_user1){
        var entry = data_user1[i]
        
        if(usernamelogin == entry.username && passwordlogin == entry.password){
            window.location.href = "curhat.jsp"
            a = entry.username
            return
            }   
        }
        if(usernamelogin != entry.username && passwordlogin != entry.password){
            alert("wrong username or password") 
        }
                
        //console.log(data_user1)
        //console.log('username = '   entry.username)
        
    })

CodePudding user response:

Just declare a before you enter the function so that you can use it later as shown below:

    let a;
    $('#btnlogin').click(function(){
            var usernamelogin = $('#usernamelogin').val()
            var passwordlogin = $('#passwordlogin').val()
            var data_user1 = JSON.parse(localStorage.getItem('data_user'))
            
            for(var i in data_user1){
            var entry = data_user1[i]
            
            if(usernamelogin == entry.username && passwordlogin == entry.password){
                window.location.href = "curhat.jsp"
                a = entry.username
                return
                }   
            }
            if(usernamelogin != entry.username && passwordlogin != entry.password){
                alert("wrong username or password") 
            }
                    
            //console.log(data_user1)
            //console.log('username = '   entry.username)
            
        })

//check if a is not null and do something with it
if(a){
  //do something with a here out of the function
}

if you wish to pass a across pages, you may use localStorage or sessionStorage as shown below to store the value of a:

a = entry.username;

localStorage.setItem("a",JSON.stringify(a))

and then later on retrieve it in another page using

const val = JSON.parse(localStorage.getItem("a"))
  • Related