I’m new to both javascript and jquery, and I’m having a small problem. It is happening with both the latest versions of Chrome and Firefox, so I don’t think it’s a browser issue.
Relevant code is here (this is a self-invoking function inside script tags on the HTML page).
(function () {
"use strict";
var submitbutton = $('#submitcommand'),
textinput = $('#textinput'),
userinput = textinput.val();
submitbutton.on('click', function() {
alert("textinput is " + textinput.val()); // => works
alert("userinput is " + userinput); // => undefined
});
}());
The first call to alert() works just fine, using ‘textinput.val()’. The second call to alert() doesn’t return any visible text, because ‘userinput’ is evaluating to ‘undefined’.
I’ve tried going into the Firebug Console and pasting the four statements (the two assignments and the two calls to alert()) in, one after the other. That works, and gets me the result I expect.
So the question is: what changes about the ‘userinput’ variable inside the on(‘click’) function? What am I not seeing here?
Thanks in advance!
As the function is self invoking, the variable will be set at page load. It is not reassessed every time the button is clicked. During page load you will probably find that:
So at the time of setting there is no value. You probably want to make the variable scoped to the button click:
Also, you will want to make sure the script block is at the bottom of the page, as then all the UI elements will be loaded in the browser when the function is invoked.