Shaq
Shaq

Reputation: 23

Select an element from drop-down list using java

I was wondering how to select an element after I found it in a ddl (drop-down list). My function can find the element but it failed to select it; I tried click but it didn't work.
Thanks
The code is:

    public static  void selectGuestCountry()
    {
        WebElement droplist = driver.findElement(By.className("sbOptions"));

        List<WebElement> allOptions = droplist.findElements(By.tagName("a"));
        System.out.println("Total options in list --> " + allOptions.size());

        for (int i=0;i<allOptions.size();i++ )
        {
            //System.out.println("++> " + allOptions.get(i).getAttribute("text"));
            if(allOptions.get(i).getAttribute("text").equals("FRANCE")) {
                System.out.println("++++>" + allOptions.get(i).getAttribute("text"));

               **allOptions.get(i).click();**// This is doesn't select the country
                break;
        }


    }
---------------------------------------------------------------

Here is the html code, thanks:

<div class="guestForm">
<input id="reservations0.guests0.id" type="hidden" value="0" name="reservations[0].guests[0].id">
<br>
<div class="form-border">
<h5>
<div class="field-col left">
<div class="field-col right">
<div>
<div class="emails">
<div class="contactInfo">
<div class="field-row">
<label class="ellipsis" title="Organization">Organization</label>
<input id="reservations0.guests0.organization" class="field" type="text" maxlength="40" value="" name="reservations[0].guests[0].organization">
</div>
<div class="field-row select-big country">
<label>
<select id="reservations0.guests0.address.country.alpha2Code" class="selectbox" onchange="populateStates(this);" name="reservations[0].guests[0].address.country.alpha2Code" sb="73833889" style="display: none;">
<div id="sbHolder_73833889" class="sbHolder">
<a id="sbToggle_73833889" class="sbToggle" href="#"></a>
<a id="sbSelector_73833889" class="sbSelector" href="#">Select Country</a>
<ul id="sbOptions_73833889" class="sbOptions" style="display: none;">
<li>
<li>
<a href="#US" rel="US">UNITED STATES</a>
</li>
<li>
<a href="#AF" rel="AF">AFGHANISTAN</a>
</li>
<li>
<li>
<li>`

Upvotes: 1

Views: 1658

Answers (2)

Alpha
Alpha

Reputation: 14026

Before the for loop in your code, click on Select Countryso that it'll show list of countries and then click on the country you want to select.

driver.findElement(By.linkText('Select Country')).click();

Upvotes: 0

ukpillai
ukpillai

Reputation: 321

Few minor tweaks to code, please read below if acceptable :

Use Select object instead of WebElement to find ddl object, with that you can use selectByIndex (easier as per your code) to select the element from list.

Upvotes: 1

Related Questions