Onchange event is not working well

2020-04-11 01:53发布

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.

4条回答
欢心
2楼-- · 2020-04-11 02:10

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
查看更多
家丑人穷心不美
3楼-- · 2020-04-11 02:12

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");
    });
});​
查看更多
太酷不给撩
4楼-- · 2020-04-11 02:21

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

查看更多
男人必须洒脱
5楼-- · 2020-04-11 02:22
function codeThatAltersTextFieldProgrammatically() {
    /* ... code ...  */

    textFieldChangeEventHandler();
};

function textFieldChangeEventHandler(){
    /* .... */
}
查看更多
登录 后发表回答