Input event not working if value is changed with jQuery val() or JavaScript

后端 未结 7 2135
孤城傲影
孤城傲影 2020-12-28 16:12

If I change the value of an input field programmatically, the input and change events are not firing. For example, I have this scenario:

7条回答
  •  一整个雨季
    2020-12-28 16:44

    jQuery listeners only work on actual browser events and those aren't thrown when you change something programmatically.

    You could create your own miniature jQuery extension to proxy this so that you always trigger the event but only have to do in one modular place, like so:

    $.fn.changeTextField = function (value) {
      return $(this).val(value).trigger("change");
    }
    

    Then, just call your new function whenever you want to update your text field, instead of using jQuery's 'val' function:

    $("#myInput").changeTextField("foo");
    

    Here's a version working with a proxy function:

        
        
            
                Test stuff
                
            
            
    
      
            
    
            
            
        
    

    For reference, this question has really already been answered here: Why does the jquery change event not trigger when I set the value of a select using val()?

    and here: JQuery detecting Programatic change event

提交回复
热议问题