How to select an option with CasperJS

后端 未结 1 1073
后悔当初
后悔当初 2020-12-21 22:13

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

相关标签:
1条回答
  • 2020-12-21 22:42

    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+"]".

    0 讨论(0)
提交回复
热议问题