user1871245
user1871245

Reputation:

Global variables not changing through function

I'm trying to get the value and name of an input box a person is currently using on keyup, however I'm having trouble with global variables being updated once the keyup function has run. They just continue to say undefined in Google Chrome developer tools.

What am I doing wrong?

$( document ).ready(function() {
                var assessName;
                var assessVal;
                var impName;
                var impVal;

                //Get the name and value of the currently selected assessed input
                $('[id^=ass]').on('keyup', function(){
                    assessName = $(this).attr('name').replace('ass-','');
                    assessVal = $(this).val();
                });

                //Get the name and value of the currently selected implemented input
                $('[id^=imp]').on('keyup', function(){
                    impName = $(this).attr('name').replace('imp-','');
                    impVal = $(this).val();             
                });

                console.log(assessName);
                console.log(assessVal);
                console.log(impName);
                console.log(impVal);
            });

Upvotes: 0

Views: 76

Answers (1)

antyrat
antyrat

Reputation: 27765

This happens because keyup events change variables after you write them to console. Events in JavaScript are asynchronous.

So if you will put your console.log call into event listener it will show exactly what you expect.

Upvotes: 2

Related Questions