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

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

    There are some ways on how to achieve it. Here, you can use the levelup HTML's oninput() event that occurs immediately when an element is changed and call the function.

    
    
    
    
    

    .

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

    Or this jQuery, input thing (just related to above example).

    
    
    
    
    

    .

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

    You can also use javascript setInterval() which constantly runs with a given interval time. It's only optional and best if you're doing time-related program.

    
    
    
    
    

    .

    var input = $("#myinput");
    
    setInterval(function() { ObserveInputValue(input.val()); }, 100);
    
    $('#change').click(function() {
      input.val(input.val() + 'x');
    });
    

提交回复
热议问题