Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onChange function is not defined

Tags:

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

like image 312
Expedito Avatar asked Sep 27 '12 12:09

Expedito


People also ask

Why is Onchange not working?

onchange is not fired when the value of an input is changed. It is only changed when the input's value is changed and then the input is blurred. What you'll need to do is capture the keypress event when fired in the given input. Then you'll test the value of the input against the value before it was keypressed.

How is Onchange defined?

Definition and UsageThe onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

Is Onchange a function?

onchange function in JavaScript plays a very pivotal role because it helps user provide an enhanced view for user to manipulate and then verify the values with an input to cross-check the value transformation with the given input and behaves complementary to the oninput function in the JavaScript.

How do you write Onchange in JavaScript?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.


2 Answers

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);
});
like image 79
James Allardice Avatar answered Dec 18 '22 09:12

James Allardice


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() {...}
like image 30
Niet the Dark Absol Avatar answered Dec 18 '22 07:12

Niet the Dark Absol