0

This works:

$(document).ready(function(){

    $("#inputbuttonid").on("click", function(){ 

        var inputtext = $("#inputtextid").val();
        alert(inputtext);

    });

});

But this doesn't work:

$(document).ready(function(){

    var inputtext = $("#inputtextid").val();

    $("#inputbuttonid").on("click", function(){ 

        alert(inputtext);

    });

});

By "works" I mean it alerts the correct information.

The only difference in the above 2 cases is that in the second, I put

var inputtext = $("#inputtextid").val();

in the outer function, whereas in the first, I put it in the inner function.

According to the JQuery manual, "local scope works through functions", meaning "any functions defined within another have access to variables defined in the outer function" (quoted from the JQuery manual).

So, why in the second case above, does the inner function not have access to "inputtext"?

3
  • 1
    That works perfectly fine -> jsfiddle.net/pVJ3L/2 Commented Apr 11, 2014 at 21:36
  • 1
    ... but if you're expecting the value to magically update itself, it wont! Commented Apr 11, 2014 at 21:37
  • it would "magically" update if you used something like knockout.js (bindings), but yes, as written; no magic. Commented Apr 11, 2014 at 21:42

2 Answers 2

5

So, why in the second case above, does the inner function not have access to "inputtext"?

It does have access1, but you are executing the statement before the user entered a value. The value is read immediately when the DOM is ready, not when the user clicks the button.

The only difference in the above 2 cases is that in the second, I put [...] in the outer function, whereas in the first, I put it in the inner function.

And this change has the consequence that that statement is now executed at a different time, at which the input field doesn't have a value yet.


1: If it didn't, you would get a reference error.

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, thanks. I'll mark your answer right as soon as SO lets me :-)
Serious question: I just noticed your SO score. Is your brain sufficiently trained that you read code like you were reading Shakespeare, and you dream in code?
0

In the 2nd example, your variable is initialized on document load, and there's no code in the click function to get the new value. This would work:

$(document).ready(function(){

    var inputtext = $("#inputtextid").val();

    $("#inputbuttonid").on("click", function(){ 
        inputtext = $("#inputtextid").val();
        alert(inputtext);

    });

});

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.