Skip to content Skip to sidebar Skip to footer

How To Select An Option With CasperJS

I try to set select option attribute to selected. But I try to avoid using nth-child in CasperJS because there are bugs in PhantomJS's nth-child. So I try to use this as the subtit

Solution 1:

The problem is the distinction between property and attribute. Browsers usually don't re-evaluate attributes when you change them in the DOM. In those cases, you would need to change the property behind that attribute on the DOM element.

In this case, you need to change the selected index. The select element has the selectedIndex property that you can change to the intended option which you can get through option.index:

function setSelectedCountry(i){
    __utils__.echo("i :"+i);
    var opt = "//*[@id='cboCountry']/optgroup[2]/option["+i+"]";
    var select = document.getElementById('cboCountry');
    select.selectedIndex = __utils__.getElementByXPath(opt).index;
    select.onblur(); // or `onchange()`
}

See this answer for more information on the option index.


"//*[@id='cboCity']/option["+i+"]" cannot work, because this expression will match options that are direct children of a #cboCity element, but you have an optgroup inbetween. Either use "//*[@id='cboCity']//option["+i+"]" or "//*[@id='cboCity']/optgroup/option["+i+"]".


Post a Comment for "How To Select An Option With CasperJS"