Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same variable in two different script tags

Tags:

javascript

Here's my first tag

<script type="text/javascript"> 
$(document).ready(function () {

    // some code

    var showWarning = true;

    // more code

});
</script>

And then I have another script tag:

<script type="text/javascript">
    function submitFormLink(){
        document.getElementById('vacationApplicationForm').action = '<c:url value="/preview-pdf"/>';
        document.getElementById('vacationApplicationForm').method = 'POST';
        document.getElementById('vacationApplicationForm').submit();
    }
    function submitFormButton(){
        if (showWarning == true){
            alert("hi");
        }
        document.getElementById('vacationApplicationForm').action = '';
        document.getElementById('vacationApplicationForm').method = 'POST';
        document.getElementById('vacationApplicationForm').submit();
    }
 </script>

And I get an error saying that showWarning is undefined. I read that variables a global in the same window. So what am I doing wrong herE ?

like image 390
Marijus Avatar asked Apr 30 '26 07:04

Marijus


2 Answers

You aren't declaring a global.

You are using the var keyword inside a function so:

  • It won't be defined until the function runs
  • It will be local to the function

If you want a global, create the variable in the global scope:

<script type="text/javascript"> 
var showWarning = true;
$(document).ready(function () {
    // some code
    // more code
});
</script>
like image 190
Quentin Avatar answered May 02 '26 21:05

Quentin


Your variable showWarning is not global. The scope is the document ready handler. If you want to make it global, you'd have to do something like this

<script type="text/javascript"> 

var showWarning = true; // now it has global scope

$(document).ready(function () {
    // some code
    // more code
});
</script>

Using global variables is considerer a bad practice in javascript so you should avoid doing this every time is possible. For more information about this, look on google for Pollution of the Global Namespace

like image 23
Claudio Redi Avatar answered May 02 '26 21:05

Claudio Redi