简体   繁体   中英

JaveScript Select the dropdown list by the text of options

Is it possible to select the dropdown list by using the display-text of the options in the console(JavaScript)?

In my workplace, I need to fill a web form every day. But the options are too much to load, so I hope to use the Chrome console to select the option instead of using the mouse to click.

For now, I can use Value to select the option, but when I try to use the text, it fails. The HTML sample and the JavaScript I used are as below. Could someone help?

Success - document.querySelector("#sel").value = 123
Fails - document.querySelector("#sel").text = "Product A"

<select>
<option value="123"> Product A </option>
<option value="243"> Product B </option>
<option value="212"> Product C </option>
<option value="466"> Product D </option>
</select>

Array.from(document.querySelectorAll('option')).find(el => el.textContent === 'Product A');

Truly sorry for the confusing example. After trying lots of solutions, the final coding as below:

var txt = prompt();
for (i = 0; i < document.querySelector("#sel").options.length; i++) {
    if(document.querySelector("#sel").options[i].text == txt){
        document.querySelector("#sel").options[i].selected = true;
        break;
    }
}

With these codes, the User can select the specific options by entering the name of the product instead of clicking the dropdown list with the mouse and crash the browser.

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