问题
I am using WATIN to complete a dynamically created form, which can contain several SelectLists (these are javascript controlled picklists). A sample of the select list format outputted is;
<select title=" " style="width: 300px;"
name="NameHere"
data-bind="value: NameHere.AnswerCode"
class="fieldInputElement pickList">
<option selected="" value=""></option>
<option class="answerTextWithNote" value="A">alpha</option>
<option class="answerTextWithNote" value="B" data-guidance="E.g. minor ">bravo</option>
<option class="answerTextWithNote" value="C" data-guidance="E.g. b">charlie</option>
<option class="answerTextWithNote" value="C" data-guidance="E.g. c">chatlie</option>
</select>
Unfortunately, watin seems to fail to select the list and any options, returning an error.
The code
window.SelectList(Find.ByName("NameHere")).Options[2].Select();
Returns an error about the index, although
string y = window.SelectList(Find.ByName("NameHere")).Option(x[1].ToString()).ToString();
will assign the correct value for the indexed option.
Can anyone advise me on how to trigger the select, as i have tried on focus() and keydown all without joy.
The selectlist is using the 'Chosen' plugin, if this helps?
回答1:
The following is somewhat not pretty.... but... it works.
Using
- IE8
- WatiN 2.0
- NUnit
- Chosen example here: http://davidwalsh.name/dw-content/jquery-chosen.php
I was unable to reproduce your index error; I can access the SelectList options by index without issue (see code below). BUT... accessing them didn't help at as Chosen has its own presentation markup.
So, instead I worked with the Chosen HTML elements instead of the SelectList and things are working better.
[Test]
public void ChosenTest()
{
IE myIE = new IE(true);
myIE.GoTo("http://davidwalsh.name/dw-content/jquery-chosen.php");
myIE.SelectList(Find.ByClass("chosen chzn-done")).WaitUntilExists(); //Needed as sometimes the controls were not fully loaded; unable to get item not found exceptions once this was added.
Console.WriteLine("ByIndex:" + myIE.SelectList(Find.ByClass("chosen chzn-done")).Options[3].Text); //To show no index out of bounds error.
// Just for reference --> myIE.SelectList(Find.ByClass("chosen chzn-done")).Options[3].Select(); //Has no effect.
string id = myIE.SelectList(Find.ByClass("chosen chzn-done")).Id;
myIE.Div(id + "_chzn").Div(Find.ByClass("chzn-drop")).ElementWithTag("li", Find.ByIndex(3)).Click();
myIE.Div(id + "_chzn").Links[0].Spans[0].Click(); //Needed or the SelectList-ish stays open.
}
Finding ByClass was done as the control IDs change on the example page. The WaitUntilExists eliminated the intermittent failures.
来源:https://stackoverflow.com/questions/7203920/watin-cant-select-an-option-from-a-select-list