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 ?
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With