使用文本从下拉列表中选择值 [英] Select value from dropdown list using the text

查看:116
本文介绍了使用文本从下拉列表中选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过使用文本而不是值或索引从下拉列表中选择值?
HTML:

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>   

剧本:

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

这不起作用,但它使用Motoren(即1140)的值。
如何使用fillSelectors将其与文本一起使用?

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 函数只能使用该值。在您的情况下,这不起作用,因为您尝试设置显示的值而不是指定的选项值。虽然,这可以很容易地扩展:

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();

参见此代码,用于SO联系页面上的完整工作示例。

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

这篇关于使用文本从下拉列表中选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆