html <input type=“text” /> onchange event not working

后端 未结 12 2517
-上瘾入骨i
-上瘾入骨i 2020-11-30 01:13

I am trying to do some experiment. What I want to happen is that everytime the user types in something in the textbox, it will be displayed in a dialog box. I used the

相关标签:
12条回答
  • 2020-11-30 01:34

    A couple of comments that IMO are important:

    • input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.

    • The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input

    • The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)

    • Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...

    • jQuery has nothing to do with this. This is all in HTML standard.

    • If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.

    My two cents.

    0 讨论(0)
  • 2020-11-30 01:36

    try onpropertychange. it only works for IE.

    0 讨论(0)
  • 2020-11-30 01:42

    Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.

    For static and dynamic inputs:

    $(document).on('input', '.my-class', function(){
        alert('Input changed');
    });
    

    For static inputs only:

    $('.my-class').on('input', function(){
        alert('Input changed');
    });
    

    JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/

    0 讨论(0)
  • 2020-11-30 01:42

    onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

    if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

    Read more about the change event here

    Read more about the input event here

    0 讨论(0)
  • 2020-11-30 01:44

    HTML5 defines an oninput event to catch all direct changes. it works for me.

    0 讨论(0)
  • 2020-11-30 01:44

    It is better to use onchange(event) with <select>. With <input> you can use below event:

    - onkeyup(event)
    - onkeydown(event)
    - onkeypress(event)
    
    0 讨论(0)
提交回复
热议问题