This simple function isn't working. Showing following error
'myfunc' is undefined
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function myfunc(){
alert('In');
}
})
</script>
<button type="button" onclick="myfunc()">Alert</button>
It's a scope issue, myfunc isn't in the global scope. When you put it inside $(document).ready()
you would only be able to call it inside the document.ready()
callback.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
//this doesn't need to be in document.ready(), it won't get called until button is already loaded anyway
function myfunc() {
alert('In');
}
</script>
<button type="button" onclick="myfunc()">Alert</button>
You can read more about how scoping works in JS at http://www.w3schools.com/js/js_scope.asp
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