Search code examples
c#.netwatin

Hot to trigger SelectList change event with my value by WatIn


I am using WatIn like you see from the title, working on vs-2012 (4.5) c#.

My goal is to make SelectList ->change event with my value.In webPage where i am working there are SelectList with values 109,110,111....,i need to make event change on this SelectList ,but with my value 2014.If i will press F12-FireBug (console) and change value by my self,and then select it from list all works fine,but i need to do this in code.

Here html code

<select name="endYear" class="dateText" onchange="setupDays('end');
verifyDate('end'); evaluateDateRange();">
<option value="109">109</option>
<option value="110">110</option>
<option value="111">111</option>
<option value="112">112</option>
<option value="113">113</option>
<option value="114">114</option>
</select>

Here what i tried ,but i get error '$' is undefined

browser.DomContainer.Eval("$('#startYear select option').attr('selected', '2014');"); 

and this

SelectList ddlStartYear = PopupDateFrame.SelectList(Find.ByName("startYear"));
  string js = string.Format("$('#startYear select option').attr('selected', '2014').change();",    ddlStartYear.Id);
  browser.Eval(js);

Do any one know if it is even posible to do?And if yes how?


Solution

  • Code to add the element to a list option is:

    string js = "";
    js = js + "var theSelectList = document.getElementById('endYear'); ";
    js = js + " AddSelectOption(theSelectList, \"Some Description\", \"2014\", true);";
    js = js + " function AddSelectOption(selectObj, text, value, isSelected) ";
    js = js + "{";
    js = js + " if (selectObj != null && selectObj.options != null)";
    js = js + "{";
    js = js + " selectObj.options[selectObj.options.length] = new Option(text, value, false, isSelected);";
    js = js + "}}";
    
    browser.Eval(js);
    

    To execute the onchange event programmatically:

    listReference.FireEvent("onchange");
    

    An alternative way to do fire the events that are executed when an event is fired is to look at the sources of the web page and if you find the calls to the js functions you can set the value of the element and then call those functions from within Watin with whatever parameters are needed and avoid to fire the event. On some cases this might work, on some other might not, but it is worth it to point this out.

    Like in this particular example you can set the value of the element and then call the three functions called on the onchange event manually, like:

    browser.Eval("setupDays('end');verifyDate('end');evaluateDateRange();");