0

I am working on a browser recording test, in which I am entering a value into an Input field with an auto search trigger functionality.

document.getElementById('InputFieldWIthSearchFunctionality').value = "Saurav";

But the search is not triggered if I set the value to the field as above.

Kindly help.

Saurav
  • 113
  • 1
  • 8
  • 3
    "change" and "input" events are not fired when an `` field is updated by JavaScript like that. You have to fire the event explicitly. – Pointy Nov 14 '19 at 13:47
  • 6
    And the problem has absolutely nothing to do with the `.getElementById()` function. – Pointy Nov 14 '19 at 13:48

2 Answers2

2

Just setting the value will not call the onchange and/or oninput event listeners of the input field. The auto search trigger is probably listening to this event.

You can dispatch both of these events manually to the input field:

const elem = document.getElementById("InputFieldWIthSearchFunctionality");

// create onchange event
const onchangeEvent = document.createEvent("HTMLElements");
onchangeEvent.initEvent("onchange", false, true);

// create oninput event
const oninputEvent = document.createEvent("HTMLElements");
oninputEvent.initEvent("oninput", false, true);

// dispatch events to the input field
elem.dispatchEvent(onchangeEvent);
elem.dispatchEvent(oninputEvent);

This definitely works in Chrome and all browsers using Chromium, I did not test any other browser, that would be up to you.

Information about manually dispatching events taken from this answer: https://stackoverflow.com/a/2856602/7846567

SteapStepper69
  • 1,247
  • 10
  • 22
0

Think of it this way... by setting the value directly using JS, you are shortcutting the typical UI that a real user would use thus causing this issue. JS should be used sparingly (almost never) if you are trying to write tests that act like a user would and now you can see why.

In Java you would do this

driver.findElement(By.id("InputFieldWIthSearchFunctionality")).sendKeys("Saurav");

which would cause the search to fire in your case.

JeffC
  • 22,180
  • 5
  • 32
  • 55