I'm trying to call a function by name .onchange
of a select but nothing happens. When the function is describled after the attribute, it works.
THIS DOESN'T WORK
HTML:
<select id="numb">
<option value="1">1</option>
<option value="2">2</option>
</select>
SCRIPT:
<script type="text/javascript">
$('#numb').change(testMessage);
</script>
<script type="text/javascript">
function testMessage(){
alert('Hello');
}
</script>
THIS WORKS
HTML:
<select id="numb">
<option value="1">1</option>
<option value="2">2</option>
</select>
SCRIPT:
<script type="text/javascript">
$('#numb').change(function(){
alert('Hello')
});
</script>
EDIT:
Ok, for all those who said me to include the function on the same script. This is not possible because the testMessage()
function is in an external .js
script included on the <head>
of the HTML.
Instead try ,
Working Jsfiddle try this:
I dont think your reference exists yet to the function here is two ways you could do it. I put the namespaced version as a suggestion because it might help clean up your code in general.
HTML:
SCRIPT:
// Namespaced and using Proxy
// Just declared
If your method is in another file make sure you include that file before the one with the event binding. Are you getting any console errors?
You must define a callback on the change function.
That should fix your problem.
It is because the handler
testMessage
is not defined when binding it to the change event.It should work if it was in the same script context like below,
Code inside
<script></script>
are executed one by one progressive from top andtestMessage
function doesn't exist inside the first<script></script>
.You have couple of options here,
Put it inside an anonymous function which will let your script to resolve the
testMessage
function later. [As suggested in Optimus Prime answer]Include the script that has
testMessage
function above thescript
that binds the testMessage like below,Try this and place in the same script tag: