Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate user interaction on input and button elements?

So I have a code here in this stackblitz example.

Basicly there is a simple form, with an input and a button. Pressing the button will copy the input's current value to a label:

enter image description here

after click:

enter image description here

html:

<input id="inputID" [(ngModel)]="inputValue" />
<button id="buttonID" (click)="set()">send</button>
<hr/>
<label> new Value: {{labelValue}} </label>
<hr/>

JS:

  labelValue = "";
  inputValue = "defaultValue";

  set(){
    this.labelValue = JSON.parse(JSON.stringify(this.inputValue));
  }

I have to simulate the user interaction using only native JS code. So I try the following (in browser console for instance):

 - document.getElementById('inputID').value = "aNewValue"; 
 - document.getElementById('buttonID').click();

The problem is this:

enter image description here

I got the default value in the label, not the current value. How can I get the right value? I suspect that it is something around reflected properties, but cannot figure out what can be the problem here.

Update: I have tried the following, with no luck either.

element = document.getElementById('inputID')
element.value = "aNewValue"; 
var ev = new Event('change', {
    view: window, 
    bubbles: true,
    cancelable: true,
  });
element.dispatchEvent(ev);
document.getElementById('buttonID').click();
like image 733
ForestG Avatar asked Jul 20 '26 01:07

ForestG


1 Answers

Angular updates the model on input event. You should trigger it manually, after you set the value.

inputElement = document.getElementById('inputID');
buttonElement = document.getElementById('buttonID');

inputElement.value = "aNewValue";
inputElement.dispatchEvent(new Event('input', {
  view: window,
  bubbles: true,
  cancelable: true
}))
buttonElement.click();
like image 56
Mihályi Zoltán Avatar answered Jul 21 '26 15:07

Mihályi Zoltán



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!