Reputation: 4365
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 ?
Upvotes: 3
Views: 3245
Reputation: 134177
You are not declaring showWarning
as a global, you are declaring it inside of a function. If you want to make it a global, you would need to change the definition to:
<script type="text/javascript">
var showWarning = true;
$(document).ready(function () {
// some code
Upvotes: 0
Reputation: 239302
Within the bare <script>
tags, it would be global:
<script type="text/javascript">
var showWarning = true;
</script>
However, you're inside a function, and you're explicitly scoping the variable to that function with the var
statement.
If you want to make a global variable inside a function, attach it to window
, which is the global context inside the browser:
<script type="text/javascript">
$(document).ready(function () {
// some code
window.showWarning = true;
// more code
});
</script>
Upvotes: 0
Reputation: 1094
if you're putting var on javascript, that means local variable. Try removing var on showWarning variable.
showWarning = true
Upvotes: -1
Reputation: 68400
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
Upvotes: 1
Reputation: 10786
The top variable only exist in the $(document).ready, you'll need to declare it outside of the function:
var showWarning;
$(document).ready(function () {
// some code
showWarning = true;
// more code
});
Upvotes: 0
Reputation: 943615
You aren't declaring a global.
You are using the var
keyword inside a function so:
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>
Upvotes: 5