familyGuy
familyGuy

Reputation: 435

How to ALWAYS select the last item in the list

I need to select the last item in a DYNAMIC list. The following is my script. Thanks!

WebElement selectElement = driver.findElement(By.name("siteKey"));
Select select = new Select(selectElement);
//select.selectByVisibleText("last item");
//select.selectByIndex(0);
//select.selectByValue("value");

Please see the page HTML below. Let me know if I can provide you with any other info. Thanks!

<div id="overview_form">
<ol>

<li>
<span>1.</span>
<label class="input_label" for="sites">Sites*</label>
<div class="select2-container select2-container-active select2-dropdown-    open" id="s2id_autogen1" style="width: 500px;">
<a tabindex="-1" class="select2-choice" onclick="return false;"     href="javascript:void(0)">   
<span>www.roger.com_20150210075155</span>
<abbr style="display:none;" class="select2-search-choice-close"></abbr>   
<div><b></b></div></a>
<input type="text" class="select2-focusser select2-offscreen" disabled="disabled">
</div>
<select style=" size="1" name="siteKey" class="select2-offscreen" tabindex="-1">

<option value="30518">www.roger.com_20150209191817</option>
<option value="30520">www.roger.com_20150209192123</option>
<option value="30522">www.roger.com_20150209192351</option>
<option value="30524">www.roger.com_20150209192910</option>
<option value="30528">www.roger.com_20150209193425</option>
<option value="30529">www.roger.com_20150209193801</option>
<option value="30531">www.roger.com_20150209194009</option>
<option value="30546">www.roger.com_20150210074133</option>
<option value="30548">www.roger.com_20150210074359</option>
<option value="30550">www.roger.com_20150210075155</option></select>

</li>
</ol>
</div>

Upvotes: 0

Views: 7764

Answers (3)

Anand Somani
Anand Somani

Reputation: 801

I tried below way, and it's working.. Maybe this will help u .

    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.echoecho.com/htmlforms11.htm");
    Thread.sleep(100l);
    driver.findElement(By.xpath("//select[@name='dropdownmenu']")).click();
    Thread.sleep(100l);
    WebElement element = driver.findElement(By.xpath("//select[@name='dropdownmenu']"));
    List<WebElement> elements = element.findElements(By.tagName("option"));
    System.out.println(elements.get(elements.size() - 1).getText());

Upvotes: 0

Anna
Anna

Reputation: 137

You can use getOptions(), it will return a list then get the size of the list

Select select = new Select(driver.findElement(By.id("siteKey")));
List<WebElement> l = select.getOptions(); 
int numElements = l.size();
select.selectByIndex(munElements);

Hope this helps

Upvotes: 1

SiKing
SiKing

Reputation: 10329

How about something like:

WebElement selectElement = driver.findElement(By.name("siteKey"));
Select select = new Select(selectElement);
select.selectByIndex(select.getOptions().size()-1);

Upvotes: 3

Related Questions