Onchange event is not working well

十年热恋 提交于 2019-12-04 04:35:06

问题


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.


回答1:


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



回答2:


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




回答3:


function codeThatAltersTextFieldProgrammatically() {
    /* ... code ...  */

    textFieldChangeEventHandler();
};

function textFieldChangeEventHandler(){
    /* .... */
}



回答4:


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


来源:https://stackoverflow.com/questions/11218553/onchange-event-is-not-working-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!