简体   繁体   中英

onChange function is not defined

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'?

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);
});

The hi function is only defined in the ready block. Outside, it doesn't exist anymore.

You don't need to wrap function definitions in .ready() , so just remove it. Alternatively, define the function like this:

window.hi = function() {...}

In your code block:

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

hi is not a global function. You can access it only inside the scope of your function(){...} , not from outside.

Since you are using jQuery, you can change the way you bind your function to the onChange event. Rather than 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>
<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();" />

onchange is only triggered when the control is blurred. Try onkeypress instead.

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

or

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

Use following events instead of onchange :

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM