6

Setting element's value is not working. It does not act like user typing. When I submit this input, popup tells me that I didn't fill input at all. How can I fill this input element just like users do?

<div class="login-input input-group" data-ng-class="{'invalid' : !valid}">
<input id="alias-input" type="text" class="form-control ng-pristine ng-valid ng-empty ng-valid-maxlength ng-touched" tabindex="1" data-ng-model="formData.alias" data-ng-keydown="sendAlias($event)" maxlength="10" data-gemius-event="click" data-gemius-parameters="['place=login','inputbox=login','met=onclick']"
    spellcheck="false">
</div>

I tried:

angular.element(document.querySelector("#alias-input")).val("foo");

document.getElementById('alias-input').value = 'foo';

7
  • I am not developer of this site. I want to create automatic test and I have problems with filling this input. Commented Dec 5, 2018 at 8:42
  • What are you using to add the test? any framework? Commented Dec 5, 2018 at 8:45
  • @xyz I am using Watin. Commented Dec 5, 2018 at 8:47
  • @Chellappan this is angularjs he is talking about. So the link to this documentation is not relevant, it is the wrong framework. Commented Dec 5, 2018 at 8:53
  • @Dafie your problem is data-ng-model overrides any change you make to the value during digest cycles. So you need to set the value after any digest cycle ends or if you can guarantee somehow the last digest cycle has occurred, change the value then. Commented Dec 5, 2018 at 8:55

2 Answers 2

14

This is what worked for me:

const event = new Event('input', { bubbles: true }); 
document.querySelectorAll('[formcontrolname = "idNumber"]')[0].value = '123456789';
document.querySelectorAll('[formcontrolname = "idNumber"]')[0].dispatchEvent(event);

This was tested on a page with Ionic 3.9.2 and Angular 5.0.3

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this helped me with a similar issue. Setting the value without calling dispatchEvent didn't allow to save the form.
@Asdrubal - This helped me too! Thank you so much! Why do I need to create a new Event() though. And dispatch it. What exactly does this do under the hood? Thank you!
1

You can set an ng-model attribute for the input element in the html like: ng-model = "inputValue". In the controller of this view, after inject the $scope, now you can set $scope.inputValue = "foo" and it will automatic update the input value.

Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.