Reputation: 373
I have a text input:
<input class="stops" id="stops" onchange="stopsChanged();">
And my current JavaScript looks like:
<script>
function stopsChanged(){
alert();
}
</script>
But when I run my code, I get this error:
ReferenceError: stopsChanged is not defined
Why am I getting this error?
Upvotes: 3
Views: 3527
Reputation: 623
You must include your JS
file on the page your <input>
is on like
<script type="text/javascript" src="path/to/your/file.js"></script>
Edit:
What probably happens is that you include your JS
file after the <input>
is loaded in the DOM
. This way HTML tries to access your function
before it's even there. Try to put your <script>
in the <head>
of your HTML
and make sure it isn't in a .ready()
function or something similar to it.
Source of above: Uncaught ReferenceError: myFunction is not defined
Upvotes: 1
Reputation: 2584
I think your problem is that you have HTML tags inside of your external javascript file. You do not need to wrap your external javascript code with html tags in the contents of the .js file.
In your HTML file though, make sure you define your script type in the opening tag if you're using an external file reference:
<script type="text/javascript" src="http://www.yoursource.com/file.js"></script>
In some browsers, it will not know how to parse the external resource without the type being defined in the opening tag.
Upvotes: 0
Reputation: 411
try it this way.
HTML:
<input id="stops">
JS:
document.getElementById('stops').onchange = function(){
console.log('test');
}
It's also better in terms of separation of function and presentation.
Upvotes: 0