简体   繁体   中英

Trying to select a value from a drop-down

One Form on the page I am accessing. This form has a dropdown with 3 options. I need to select the third option. Accessing the webpage from a C# program with cefsharp library (embedded web browser).

I can change the displayed text using

document.forms[0].getElementsByClassName('css-0 Select__single-value')[0].innerText="Keep in-play";

but this has not been registered. Have also tried to trigger input and change events but it is still not recognising my selection. Any suggestions?

Here is the original DOM for the form:

 <div class="bet-widget-optional-params"> <div class="bet-params"> <div class="param-wrapper"><span class="param-label"><a class="link" href="https://help.smarkets.com/hc/en-gb/articles/115003946591" target="_blank">Time In Force</a></span> <div class="param-select"> <div class="css-0 Select custom-select-box Select menu-on-click"> <div class="css-0 Select__control"> <div class="css-0 Select__value-container Select__value-container--has-value"> <div class="css-0 Select__single-value">Default</div><input id="react-select-bet-param-selector-input" readonly="" tabindex="0" class="css-14uuagi" value=""></div> <div class="css-0 Select__indicators"><span class="css-0 Select__indicator-separator"></span><span aria-hidden="true" class="Select__arrow-zone"><span class="Select__arrow"></span></span> </div> </div> </div> </div> </div> </div> </div>

In JavaScript you can set the selectedIndex property.

elem.selectedIndex = 2;

Setting -1 will remove any selection, and any positive integer will select that item in the list (0-indexed)... so if you want the 3rd item, just set it to 2 .

HTMLSelectElement.selectedIndex docs

The property works as a getter too, so if you want to know which element is selected, you can request it like:

var currentSelectedIndex = elem.selectedIndex;

Full interactive example below:

 var selectElem = document.getElementById('select'); var pElem = document.getElementById('p'); var buttonElem = document.getElementById('button'); selectElem.addEventListener('change', function() { var index = selectElem.selectedIndex; pElem.innerHTML = 'selectedIndex: ' + index; }); buttonElem.addEventListener('click', function(){ selectElem.selectedIndex = 2; });
 <p id="p">selectedIndex: 0</p> <select id="select"> <option selected>Option A</option> <option>Option B</option> <option>Option C</option> <option>Option D</option> <option>Option E</option> </select> <input type="button" id="button" value="Set it to C (2)"/>

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