下拉列表获取非选定项目的文本

时间:2012-10-18 08:33:37

标签: jquery jquery-selectors

我在同一容器中有多个下拉列表,其中包含“any”选项作为其第一项。我想要获取所选的单个选项的文本,或者如果选择“any”(值= 0),则获取该列表中的REST OF选项的数组(但不是“any”选项) 。序列化当然不会起作用,因为我在某些列表上寻找未选择的选项。

在我的简单测试中,以下工作用于在单个选择中获取未选择的选项文本的文本:

var opts = $('select > option:not(:selected)').map(function() { return this.text; }).get();

但是当我翻译它以支持尽可能多的选择时,我的容器(未知数字)我遇到了麻烦。 map(..)。get()/ array concat对我来说是最明显的方式,循环/推送似乎很乱(即使它只是在jquery中隐藏相同的过程)

    var val = [];
    jQuery("select :selected", "#container").each(function () {
        if ($(this).val() == 0) { // "any"
            // _val.concat($(this).siblings().map(function() {return this.text; }).get()); // didn't work, even though siblings matches everything OTHER THAN the selected item
            _val.concat($('option:not(:selected)', $(this).parent()).map(function() { return this.text; }).get()); // didn't work either, even though this is all the options not selected mapped to an array
            //for (var i=0;i<$(this).siblings().length-1;i++) _val.push($(this).siblings().get(i).text()); // no; even though it is a <HTMLOptionElement>; ignore the potential bug in i if you spot it, it doesn't affect me!
        } else {
            _val.push(this.text); //$(this).text());
        }
    });
    _val.push(jQuery("input","#container").val());
    alert(_val.join(" ").toLowerCase()); // all my drop downs + my fields
像往常一样,这将是一些愚蠢的小东西,这对我来说太明显了(而且已经很晚了)。

2 个答案:

答案 0 :(得分:0)

我已将您的脚本修改为:

var val = [];

jQuery("select", "#container").each(function() {
    if ($(this).val() == 0) {
        val.push($(this).find('option:not(:selected)').map(function() {
            return this.text;
        }).get());
    } else {
        val.push($(this).find('option:selected').map(function() {
            return this.text;
        }).get());
    }
});

alert(val.join(", ").toLowerCase()); 

请参阅此FIDDLE以检查它是否符合您的预期。

答案 1 :(得分:0)

这是我想出的对我而言的解决方案:

    var _val = [];
    jQuery("select", "#container").each(function() {
        if ($(this).val() == 0) {
            jQuery.merge(_val, $(this).find('option:not(:selected)').map(function() { return this.text.toLowerCase(); }).get());
        } else {
            _val.push($(this).find('option:selected').map(function() { return this.text.toLowerCase(); }).get());
        }
    });
    _val.push(jQuery("input","#container").val().toLowerCase());