Reputation: 4047
I am getting this error validate_allocation is not defined
when trying to execute a function from a static file. Any idea why?
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="static/main.js"></script>
<script>
validate_allocation();
</script>
main.js
$(function() {
alert('test'); // I can see this, so the file is imported for sure
function validate_allocation(){
alert('test');
}
});
Upvotes: 0
Views: 1257
Reputation: 485
Remove the Validate_allocation function from jquery onload function. Since you are writing in that function it will be scoped to that function only.
function validate_allocation(){
alert('test');
}
$(function() {
alert('test'); // I can see this, so the file is imported for sure
});
This will make the function globally accessible
Upvotes: 0
Reputation: 1029
The purpose of $(function() { ... });
is to run the code inside once the page has finished loading. As others have said, you're defining a function not only after the page has finished loading (and therefore after the call is made in your HTML file), but it is also limited to the scope of that block. It can safely be moved out of the block:
// Declare function at the root of the document and make it accessible to the HTML page
function validate_allocation(){
alert('test');
}
// Actions to perform when the page has completed loading
$(function() {
alert('test'); // I can see this, so the file is imported for sure
});
Upvotes: 1