onChange function is not defined

Expedito picture Expedito · Sep 27, 2012 · Viewed 83k times · Source

This has got to be something simple. I searched the internet and only found syntax errors as the cause of this problem, but I can't find a 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 the HTML :

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

On pageload the function hi is called as expected, but my onChange event causes a Firebug error, saying the function is not defined. I'm really stumped. Did I mispell 'hi'?

Answer

James Allardice picture James Allardice · Sep 27, 2012

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

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