Select value from dropdown list using the text

和自甴很熟 提交于 2019-12-18 09:45:39

问题


How do you select a value from a dropdown list, by using the text, instead of the value or the index? The HTML:

<select   name="category_group" id="category_group"  sel_id="" >
    <option value="0" selected="selected">Kies de rubriek</option>

    <option value='1000' style='background-color:#dcdcc3;font-weight:bold;' disabled="disabled" id='cat1000' >

            -- VOERTUIGEN --

    </option> 

    <option value='1020'  id='cat1020' >
        Auto's

    </option> 

    <option value='1080'  id='cat1080' >
        Auto's: Onderdelen

    </option> 

    <option value='1040'  id='cat1040' >
        Motoren

    </option> 

    <option value='1140'  id='cat1140' >
        Motoren: Onderdelen

    </option>
</select>   

the script:

this.fillSelectors('form[name="formular"]', {
    'select[name="category_group"]': 'Motoren'
}, false);      

This does not work, but it works using the value of "Motoren" (which is 1140). How can I make it work, using fillSelectors, with the text?


回答1:


CasperJS' fill functions only work by using the value. In your case this doesn't work because you're trying to set the shown value not the assigned option value. Though, this can be easily extended:

casper.selectOptionByText = function(selector, textToMatch){
    this.evaluate(function(selector, textToMatch){
        var select = document.querySelector(selector),
            found = false;
        Array.prototype.forEach.call(select.children, function(opt, i){
            if (!found && opt.innerHTML.indexOf(textToMatch) !== -1) {
                select.selectedIndex = i;
                found = true;
            }
        });
    }, selector, textToMatch);
};

casper.start(url, function() {
    this.selectOptionByText('form[name="formular"] select[name="category_group"]', "Motoren");
}).run();

See this code for a fully working example on the SO contact page.



来源:https://stackoverflow.com/questions/26792260/select-value-from-dropdown-list-using-the-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!