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

后端 未结 7 2142
孤城傲影
孤城傲影 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:36

    Looks like there's no way, other than using .trigger().

    Let's try the same thing using .change() event:

    var $input = $("#myinput");
    
    $input.on('change paste keyup', function() {
      alert($(this).val());
    });
    
    $('#change').click(function() {
      $input.val($input.val() + 'x').trigger("change");
    });
    
    
    
    

    Or you need to trigger it manually:

    $('#change').click(function() {
      $input.val($input.val() + 'x').trigger("input");
    });
    

    Snippet

    var $input = $("#myinput");
    
    $input.on('input', function() {
      alert($(this).val());
    });
    
    $('#change').click(function() {
      $input.val($input.val() + 'x').trigger("input");
    });
    
    
    
    

提交回复
热议问题