简体   繁体   中英

Select value from dropdown list using the text

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM