I am trying to set the value of a search box using JavaScript in Chrome’s console, as shown in this screenshot:
I use the following code to set the value:
document.querySelector("body > main > eup-orders > div > div > div > div.table-header.form-inline.clearfix.with-search > form > div > div > input").value = "Hello World";
Next, I want to trigger the search by clicking the search button, as shown in this screenshot:
Here’s the code I use to click the button:
document.querySelector("#btn-search").click();
The problem: Although the value is successfully set in the search field, the search does not start unless I manually click inside the search field.
Question: Is there a way to programmatically trigger the update of the search field so it works without manual interaction?
Alternatively, is it possible to simulate pressing the Enter key?
Often, pages listen for input or change events on a text field to update internal state. After setting the value, you can programmatically dispatch those events so the page “knows” the input has changed.
const inputField = document.querySelector(
"body > main > eup-orders > div > div > div > div.table-header.form-inline.clearfix.with-search > form > div > div > input"
);
inputField.value = "Hello World";
// 2. Dispatch relevant events (input and/or change, depending on site behavior)
inputField.dispatchEvent(new Event("input", { bubbles: true }));
inputField.dispatchEvent(new Event("change", { bubbles: true }));
document.querySelector("#btn-search").click();
Alternatively, you can also use the enter key like this:
const inputField = document.querySelector("...your selector...");
inputField.value = "Hello World";
inputField.dispatchEvent(new Event("input", { bubbles: true }));
// Now simulate Enter key
const enterEvent = new KeyboardEvent("keydown", {
bubbles: true,
cancelable: true,
key: "Enter",
code: "Enter",
keyCode: 13,
which: 13
});
inputField.dispatchEvent(enterEvent);