Reputation: 405
$(document).ready(function() {
var v = $("input[name=link]").val();
$('p').on('click', function () {
console.log(v);
console.log('hello');
})
});
Above is a jQuery/JS code that I have written. It is supposed to get the value in an input field, and print it to the console when i click on a paragraph.
I already declare v
as a global variable, but it's not printing to the console. It only works if I place the var v
declaration into the function making it local variable. Why it is like this? I thought global variables are always supposed to work all around the whole code. Pls educate me on this.
Upvotes: 3
Views: 161
Reputation: 121998
The problem is you have'nt change the v
value after you change the text in the textbox
When ready called you assigned the value of the textbox.i.e empty.
see the below code howit works.
var v = 10;
alert("" + v);
myFunction();
function myFunction()
{
v = 20;
}
alert("" + v);
Upvotes: 0
Reputation: 382132
This isn't a problem of scope, v
is perfectly visible from the callback you give to jQuery as event handler.
The problem with your code is that v
is evaluated immediately, as soon as the document is ready. If you change the value of the input, v
isn't changed, it keeps being empty if it was initially empty. v
isn't some kind of pointer to the input's field, there is no reason for it to change when the input is changed.
To ensure the value of the field at click time is used, use this code :
$(document).ready(function() {
$('p').on('click', function () {
var v = $("input[name=link]").val();
console.log(v);
console.log('hello');
})
});
Upvotes: 4