0

I am setting a variable in an if...else statement. However, when I try to call the variable in another function, I get the error that the variable is not defined. How can I set a global variable?

function username_check(){  
username = $('#username').val();
if(username == "" || username.length < 7 || username.indexOf(' ') > -1){
    usernameFilled = 0;
else{
    usernameFilled = 1;
}   
}

function email_check(){ 
email = $('#email').val();
if(email == "" || email.indexOf(' ') > -1) {
    emailFilled = 0;
}else{
    emailFilled = 1;
}
}

function password_length(){ 
password = $('#password').val();
if(password == "" || password.indexOf(' ') > -1) {
    passwordFilled = 0;
}else{
    passwordFilled = 1;
}
}

function password_check(){  
  password2 = $('#password2').val();
  password = $('#password').val();
  if(password2.length > 7 && password2 == password) {
    password2Filled = 1; /**setting the variable**/
  }else{
    password2Filled = 0;
  }
}

function upload(){
if (usernameFilled == 0 || emailFilled == 0 || passwordFilled == 0 || password2Filled == 0) {
    alert('All fields are required');
}else{
    /**upload to database**/
}
stevenspiel
  • 5,775
  • 13
  • 60
  • 89
  • Please reproduce your issue on jsfiddle – zerkms Jul 04 '12 at 02:47
  • 1
    are you sure you're calling `upload` ***after*** you call `password_check` ? – Alex Jul 04 '12 at 02:49
  • @Tats_innit: global variable shouldn't be declared in a special way. It's declaration goes on first initialization entry – zerkms Jul 04 '12 at 02:49
  • @tats_innit, this is a dumb question, but didn't I declare it on the 5th line? Is there somewhere else it needs to happen? – stevenspiel Jul 04 '12 at 02:50
  • @zerkms, Working on a jsfiddle... – stevenspiel Jul 04 '12 at 02:50
  • @mr.musicman: now try to find the difference. If it works there, but doesn't in your code - we barely could help – zerkms Jul 04 '12 at 02:51
  • @zerkms Hiya bruv, I have a habit of putting `var` i.e. is it true that we can use the identifier straight away? `:)` – Tats_innit Jul 04 '12 at 02:53
  • @Xander I believe so. upload() is placed after password_check() in my script, just as it is here. – stevenspiel Jul 04 '12 at 02:53
  • 3
    @Tats_innit: - `var` is what differs local variables from global ones. And the question is about globals. If you don't specify `var` - the variable becomes global, and `a = 1;` equals to `window.a = 1;` – zerkms Jul 04 '12 at 02:53
  • @mr.musicman then `password2Filled` must get it's value changed in between calls ... – Alex Jul 04 '12 at 02:54
  • @mr.musicman I usualluy do this `var currentObject =` http://praveenbattula.blogspot.co.nz/2009/09/jquery-and-how-to-declare-variables.html `:)` BTW - no question is dumb question man! `:)` – Tats_innit Jul 04 '12 at 02:54
  • @zerkms, correction. I am currently working on putting together a jsfiddle. I'll have it soon. – stevenspiel Jul 04 '12 at 02:54
  • @Tats_innit: even though you usually do that - there is a difference and you probably need to figure it our until you give more advices ;-) – zerkms Jul 04 '12 at 02:55
  • @zerkms Ah man Thank-you, I was confused abt that. - can you please flick me any mild reading link +1. – Tats_innit Jul 04 '12 at 02:55
  • @Xander, I am not joking. I literally copied and pasted the script onto here. There is nothing in between them. – stevenspiel Jul 04 '12 at 02:56
  • 1
    @mr.musicman then do the same for the calls to these functions (copy-paste the calls to `password_check` and `upload`! – Alex Jul 04 '12 at 02:56
  • @zerkms Cheers bruv for clearing confusion **If anyone keen** - http://stackoverflow.com/questions/2866866/jquery-global-variable-best-practice-options ; Cheers, (I need coffee now) Thanks again man! – Tats_innit Jul 04 '12 at 02:59

3 Answers3

1

Rather than setting a global variable just return password2Filled and save it outside the function. Then you can pass it into the next function.

ie

function password_check(){  
   password2 = $('#password2').val();
   password = $('#password').val();
   if(password2.length > 7 && password2 == password) {
       password2Filled = 1; /**setting the variable**/
   }else{
       password2Filled = 0;
   }
   return password2Filled;
}

function upload(password2Filled)
{
    if (password2Filled == 0) { /**calling the variable**/
        alert('All fields are required');
    }else{
        /**upload to database**/
    }
}

....

var passwordsOk = password_check();
upload(passwordOk);

Try and avoid global variables, they clutter up the program and make it difficult to see the flow of the code and to create code that is reusable.

Ben
  • 10,931
  • 9
  • 38
  • 47
  • i did try that. Might have done something wrong in there, I just kept getting the error that the variables weren't defined. I'll have to try it again... – stevenspiel Jul 04 '12 at 03:06
1

You're probably calling the functions in the wrong order, or doing something else wrong, cause it works just fine for me, edited the code slightly to test it:

function password_check(){  
  var password2 = $('#password2').val(), 
      password = $('#password').val();
  password2Filled = (password2.length > 7 && password2 == password) ? 1:0;
}

function upload(){
    console.log(password2Filled); //prints 0 or 1 just fine ???
}

$("#btn").on('click', function() {
    password_check();
    upload();
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • It's true, I am trying to call more functions than just one. I'll update my question to show you. Maybe you can spot the error. Thanks! – stevenspiel Jul 04 '12 at 03:00
0

You create global variables in JavaScript by defining them outside of the scope of all functions. Like so:

<script type="text/javascript">
var globalVariable;


function blah()
{
    globalVariable = "something";
}

function anotherFunction()
{
    alert(globalVariable);
}
</script>

The ECMAScript / JavaScript documentation states that a "Global Object" should be created outside of any execution context.

Alex W
  • 37,233
  • 13
  • 109
  • 109
  • Actually, you declare global variables by using the window object, like window.myVar = something, and just skipping the 'var' keyword will do that no matter what scope it's in. – adeneo Jul 04 '12 at 03:09
  • @adeneo Do you have any official documentation or sources to cite that instruct you to use that method? Just because it works doesn't mean it's a documented best practice. – Alex W Jul 04 '12 at 03:14
  • Nope, but unless you're using ECMA 5 in strict mode it will work just fine, but there's nothing wrong with declaring variables, and it is both good practice and recommended as far as I know, but failing to declare in the global scope is almost certainly not the problem in this case. – adeneo Jul 04 '12 at 03:20
  • Actually, the MDN documentation is [here](https://developer.mozilla.org/en/JavaScript/Reference/Statements/var)! -- `Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable (also a property of the global object). The difference is that a declared variable is a non-configurable property of the global object while an undeclared is configurable.` – adeneo Jul 04 '12 at 03:22
  • @adeneo Read carefully: http://stackoverflow.com/questions/4862193/javascript-global-variables – Alex W Jul 04 '12 at 03:40
  • Well, it says the exact same thing? A variable without the var keyword creates a property on the window object implicitly, no matter the scope. Declaring the variable outside any function scope is still not the right answer, and all documentation so far says that the way it's done in the OP's code is just fine. Case pretty much closed. – adeneo Jul 04 '12 at 04:13
  • @adeneo We are both right in some sense. I am merely stating that it is recommended, and more clear to use global variables the way I have done it above. As for the OP, I directly answered his question: How can I set a global Variable? – Alex W Jul 04 '12 at 04:15