Chrome: Simulate keypress events on input text field using javascript

前端 未结 2 762
暖寄归人
暖寄归人 2020-12-01 16:43

There is a lot of contents on this in stack overflow but none seems to work for my case. I have an input text field and I want to simulate keypress event to fill the text fi

相关标签:
2条回答
  • 2020-12-01 17:21

    IMHO you're going about this all wrong. Angular is not "listening" to keypress or the like. It is listening to change and input events. See the example below. It does (admittedly it is simple) what you need.

    var iButton = document.getElementById('inputButton');
    iButton.addEventListener('click', simulateInput);
    
    var cButton = document.getElementById('changeButton');
    cButton.addEventListener('click', simulateChange);
    
    function simulateInput() {
      var inp = document.getElementById('name');
      var ev = new Event('input');
      
      inp.value =inp.value + 'a';
      inp.dispatchEvent(ev);
    }
    
    function simulateChange() {
      var inp = document.getElementById('name');
      var ev = new Event('change');
      
      inp.value = 'changed';
      inp.dispatchEvent(ev);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="">
     
    <p>Input something in the input box:</p>
    <p>Name : <input id="name" type="text" ng-model="name" placeholder="Enter name here"></p>
    <h1>Hello {{name}}</h1>
    
    </div>
    
    <button id="inputButton">I simulate the "input" event.</button>
    <button id="changeButton">I simulate the "change" event.</button>

    0 讨论(0)
  • 2020-12-01 17:22

    You will not be able to fire an event that will cause text to populate an input. See this snippet from MDN:

    Note: manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

    Thanks @gforce301

    Your best bet may be to set the value and then dispatch an event.

    0 讨论(0)
提交回复
热议问题