简体   繁体   English

使用文本从下拉列表中选择值

[英]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: 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).这不起作用,但它可以使用“Motoren”的值(1140)。 How can I make it work, using fillSelectors, with the text?如何使用 fillSelectors 使其与文本一起工作?

CasperJS' fill functions only work by using the value. CasperJS 的fill函数只能通过使用值来工作。 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.有关 SO 联系页面上的完整工作示例,请参阅此代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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