3
$(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.

2 Answers 2

4

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'); 
    })  
});
Sign up to request clarification or add additional context in comments.

2 Comments

Oh ya... FACEPALM myself. Keep forgetting, I think I'll keep it local the, or add a keyup() function. Anything better to detect change of the input field rather than keyup()?
@ArmeshSingh Better use the change event : $("input[name=link]").on('change', function(){ console.log($(this).val()) });.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.