Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript var inside function

I'm newbie with javascript and I want to understand why this isn't working:

var firstName = $("#firstName").val();

$("#account").on('submit', function() {
     console.log(firstName); // Empty value
});

jsfiddle: FIDDLE

like image 774
Amanda Thompson Avatar asked Feb 06 '23 17:02

Amanda Thompson


1 Answers

The way your code is written, it grabs the value of the firstname field when the page is first loaded and stores that in the variable firstName. Then, sometime later it outputs that stored value to the console. If you want the current value of that field, you have to fetch the current value at the time you output it like this:

$("#account").on('submit', function() {
     var firstName = $("#firstName").val();   // get current value
     console.log(firstName); 
});
like image 84
jfriend00 Avatar answered Feb 09 '23 06:02

jfriend00