Jump to content

Using a local variable globally?


afish674
 Share

Recommended Posts

I have a variable (userBday) within a function which I want to use globally, how can I do this?

$("#submit").click(function() {		var userBday = $("#bDay").val();});

At the moment I've just moved the closing bracket to the end of the script and put everything that I want to happen after this function within it. This doesn't seem like the right way though! Thanks

Link to comment
Share on other sites

Do I need to assign a value to userBday whilst declaring it outside of the function? If I declare it as below then it doesn't work, if I change it to 'var userBday = ""' then I get a blank string.

var userBday; $("#submit").click(function() {  userBday = $("#bDay").val();}); var bDaySplit = userBday.split("-");var birthDay = bDaySplit[2];var birthMonth = bDaySplit[1];var birthYear = bDaySplit[0];

What I want to do is have this function get the value from the date picker box (#bDay) when the #submit button is clicked. Then outside of this function have it split the date up so I can access the day month and year.

Link to comment
Share on other sites

Declare them all as global and then set their values inside the function.

var userBday;var bDaySplit;var birthDay;var birthMonth;var birthYear;$("#submit").click(function() {  userBday = $("#bDay").val();  bdaySplit = userBday.split("-");  birthDay = bDaySplit[2];  birthMonth = bDaySplit[1];  birthYear = bDaySplit[0];});

The reason your code is failing is because all the code outside of the function is executed first. All of it, as soon as the page has loaded, and then it does not run anymore.

Link to comment
Share on other sites

A statement(s) inside a function is only executed, when a command is passed to the browser to access it, then execute(). In your case, you got an error, because the rest code outside the fuction where executed when the browser loaded, and the userBday var was inside a fuction (a function that wasn't called), so userBday was never set, before the rest code where run by the browser.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...