简体   繁体   中英

How do I make sure a keyboard event is firing when manually manipulating an input in Javascript?

I am on the site RedBubble.com and want to simulate someone typing into the search box. When someone types something in there is a window that shows data like search suggestions etc...

I open up my console. I type in the following in:

let searchbar = document.querySelector('input[name="query"]');
searchbar.value = 'Cat';

This results in the search bar showing the word cat but it does not produce the focus or fire the window that typically shows up if you click on the search box.

On google I was able to do something similar with the search bar and then get it to show the keyword suggestions when using code like this:

searchbar.click();

But I am missing something when trying to do the same on the RedBubble site within my console.

This is what I am hoping to see: 搜索栏弹出框的图片

The suggestion dialog window is triggerd by a focus event on the <input name="query"> element. You can simulate that event by creating and dispatching your own event.

const focusEvent = new Event('focus');
document.querySelector('input[name="query"]').dispatchEvent(focusEvent);

Though, it does not seem possible to show results based on the value of the input. That logic seems to be dictated by the logic in the React app.

That's because the click event is not on the input but instead on the search icon button,

You need to do:

document.querySelector('button[type=submit]').click()

you can add this:

searchbar.addEventListener("input", function(){
    //do something
});

to actively listen for inputs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM