jquery change not working incase of dynamic value change

后端 未结 4 1819
抹茶落季
抹茶落季 2021-01-02 17:24

In jQuery how can I track onchange event if the value of textbox is changing dynamically from some other event. I tried this but its not working:



        
4条回答
  •  粉色の甜心
    2021-01-02 17:50

    I was looking for a solution like this which would trigger without the user needing to leave the element, but which would work for all cases, including those identified by Jakub in his post. I.e.

    • Normal typing
    • Pasting via mouse
    • Autocomplete

    I also ideally wanted a jQuery solution as I was using various jQuery selectors etc and didn't want the hassle of "unwrapping" my jQuery objects to get to the DOM element.

    I went for a solution using 3 different event triggers - see the comments in the code sample below for why:

    var valuechanged = function () {
        // do something
    };
    var inputtowatch = $('.selector');
    inputtowatch.on('input', valuechanged);
    inputtowatch.on('keyup', valuechanged); // input event is buggy and doesn't catch delete/backspace in IE, but can't just use keyup alone as that doesn't catch paste and automcomplete
    inputtowatch.on('propertychange', valuechanged); // input event not supported in IE < 9
    

    I expected that using multiple events like this might result in the function being fired multiple times. In my testing in Firebug, that didn't happen. However, I was in the fortunate position of not minding if the function ran "too many" times and so didn't test this particular aspect further (e.g. other browsers).

提交回复
热议问题