3

I created a following html page.

<html>
    <head></head>
    <body>
        <input type="text" value="" id="Textbox" onchange="alert('text change');" />
        <input type="button" value="" onclick="document.getElementById('Textbox').value = 'Hello';" />
    </body>
</html>

When the entered text is inputted into the textbox, the onchange event is working well. I wrote a code that when the button is clicked, the 'Hello' text is inputted into the the textbox. But the onchange event of the textbox is not working well. How can I catch change event? Thanks.

zanhtet
  • 2,040
  • 7
  • 33
  • 58

4 Answers4

5

Programmatically changing the value doesn't fire a change event, that only occurs if the user focuses the element, changes the value and then puts focus elsewhere.

Options are to manually call the onchange listener, dispatch a change event on the element, or manually bubble the change event by going up the DOM looking for parents with an onchange listener and calling them.

Here is an answer that seems to fit the bill: trigger onchange event manually

Some links:

  1. MDN dispatchEvent (standards compliant): https://developer.mozilla.org/en/DOM/element.dispatchEvent
  2. MSDN fireEvent (IE proprietary): http://msdn.microsoft.com/en-us/library/ie/ms536423(v=vs.85).aspx
Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209
0

If you want to capture every change use the keydown event. onChange only fire after an input is blurred if I remember correctly.

hobberwickey
  • 6,118
  • 4
  • 28
  • 29
0
function codeThatAltersTextFieldProgrammatically() {
    /* ... code ...  */

    textFieldChangeEventHandler();
};

function textFieldChangeEventHandler(){
    /* .... */
}
Alex
  • 34,899
  • 5
  • 77
  • 90
-1

well currently according to your code, when you get out of the text box the event works,

you need to try OnKeyPress check it here http://jsfiddle.net/EBMyy/

see this code

$(document).ready(function(){
    $("#Textbox").keypress(function(){
        alert("Text Changed");
    });
});​
mfadel
  • 887
  • 12
  • 32
  • 2
    Your answer misses the point and there is no jQuery tag on the question so providing a jQuery specific answer isn't helpful. The OP says that the onchange listener works fine for user input, it's programmatic changes of the value that are the issue. – RobG Jun 27 '12 at 23:20
  • 1
    jquery is not the default js framework for web development – gonephishing Jan 29 '17 at 14:20