OnChange not defined

It should be something simple. I searched the Internet and only found syntax errors as the cause of this problem, but I can not find the syntax error.

Here's the javascript:

<script type="text/javascript" src="http://localhost/acrilart/javascript/jquery-1.6.4.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ function hi(){ alert('hi'); } hi(); }); </script> 

And HTML:

 <input type="text" name="cep" value="" id="cep" class="required cep field" onChange="hi()" /> 

In pageload, the hi function is called as expected, but my onChange event onChange a Firebug error saying that the function is undefined. I'm really at a standstill. Am I saying hello?

+13
source share
6 answers

The hi function is only available in the area inside the ready event handler. Move it outside the event handler or handle the binding inside (and remove the inline event handler attribute from the markup):

 $(document).ready(function(){ function hi(){ alert('hi'); } $("#cep").on("change", hi); }); 
+19
source

The hi function is defined only in the ready block. Outside, it no longer exists.

You do not need to wrap function definitions in .ready() , so just delete it. Alternatively, define a function as follows:

 window.hi = function() {...} 
+5
source

In your code block:

 <script type="text/javascript"> $(document).ready(function(){ function hi(){ alert('hi'); } hi(); }); </script> 

hi not a global function. You can access it only within the scope of function(){...} , and not outside.

Since you are using jQuery, you can change the way your function is bound to the onChange event. Instead of calling it from the html tag, you can write:

 <script type="text/javascript"> $(document).ready(function(){ function hi(){ alert('hi'); } hi(); $('#cep').on( 'change', function(){ hi(); } ); }); </script> 
+2
source
 <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> function hi(){ alert('hi'); } </script> <input type="text" name="cep" value="" id="cep" class="required cep field" onKeyPress="javascript:hi();" /> 
+2
source

onchange only starts when the control is blurred. Instead, try onkeypress .

 $("#cep").on("change", function() { alert(1); }); 

or

 <input type="text" name="cep" value="" id="cep" class="required cep field" onkeypress="hi()" /> 

Use the following events instead of onchange :

 - onkeyup(event) - onkeydown(event) - onkeypress(event) 
+1
source

Try so, it can reduce your efforts.

 <select (change) = "myFunc($event)"> <option>option</option> </select> 
0
source

All Articles