Select value from dropdown list using the text

2019-01-29 12:22发布

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条回答
\"骚年 ilove
2楼-- · 2019-01-29 12:59

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.

查看更多
登录 后发表回答