jquery - 从下拉列表中检索选择并填充列表

标签 jquery element populate

我需要检索页面上每个下拉列表的所有选定值,并使用这些值填充无序列表。当然,每个项目都有一个新的 li 元素。

目前我有这个:

$(document).ready(function() {
    $("select").each(function() {
        var sel = "";
        $(this).find(":selected").each(function() {
            sel += $(this).text() + " ";
        });
        $(".size-result").text(sel);
    });
});​

如何使用它来创建新的 li 元素,然后插入文本?

多亏了wirey,我终于可以使用它了:

$(document).ready(function() {
    $("select").change(function() {
        var sel = "";
    $(".option-select option:selected").each(function () {
       sel += $(this).text() + " ";
    });
    $(".result").empty().append(sel);
    }); 
});

有没有办法可以否定每个下拉列表的第一个条目?由于它是“选择...”或“选择一个...”值,我想阻止它显示,因为它是选择中的第一个值。

最佳答案

$(document).ready(function() {
    var newLI = '';
    $("select option:selected").each(function() {           
           newLI += '<li>' + $(this).text() + "</li>";              
    });
    $('ulselector').append(newLI);
});​

编辑:

您可以监听每个下拉列表中的更改并在每次更改时重新更新列表

$(document).ready(function() {        
    $('select').change(function(){ // <-- bind change event handler to the drop downs
        var newLI = '';
        $("select option:selected").each(function() {   // <-- then iterate each time it changes   
              newLI += '<li>' + $(this).text() + "</li>";              
        });
        $('ulselector').empty().append(newLI); //<-- empty() to remove old list and update with new list
    });
});​

再次编辑:

您可以检查所选值的索引是否为 0..如果是则不显示

$(document).ready(function() {
    $('select').change(function() { // <-- bind change event handler to the drop downs
        var newLI = '';

        $("select option:selected").each(function() { // <-- then iterate each time it changes   
            if ($(this).index() !== 0) { // <-- only if not default
                newLI += '<li>' + $(this).text() + "</li>";
            }    
            $('ul').empty().append(newLI); //<-- empty() to remove old list and update with new list
        });
    });
});

http://jsfiddle.net/wirey00/bKWpg/

关于jquery - 从下拉列表中检索选择并填充列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12009343/

相关文章:

javascript - 通过按回车#2 阻止用户提交表单

python - 使用多个元素条件在数据框中设置值

浏览器中的 CSS - "inspect element"部分不会更改应用的 css 规则

html - 使用 JSON 数据填充 HTML 表

c - 使用函数在c中填充并返回字符串数组

javascript - 如何使用控制台选择N个复选框?

javascript - 条形图 D3.js 错误 : Invalid value for <rect> attribute

jquery - 鼠标失控时如何隐藏工具提示

c++ - 将字符串拆分为单词的 vector <string>

java - 查找 String 数组中索引处元素的子字符串