javascript - 使用 Javascript 从 HTML 列表框(多选)中的项目生成逗号分隔的字符串

标签 javascript html string textbox listbox

<分区>

因此,如果您有一个 html 列表框,也称为多选,并且您想要生成一个逗号分隔的字符串来列出该列表框中的所有值,您可以使用以下示例来实现。 list_to_string() js 函数是这里唯一重要的事情。您可以在 http://josh.gourneau.com/sandbox/js/list_to_string.html 上玩这个页面

<html>
<head>
    <script>
    function list_to_string()
    {
        var list = document.getElementById('list');
        var chkBox = document.getElementById('chk');
        var str = document.getElementById('str');
        textstring = "";
        for(var i = 0; i < list.options.length; ++i){
            comma = ",";
            if (i == (list.options.length)-1){
                comma = "";
            }
            textstring = textstring + list[i].value + comma;
            str.value = textstring;
        }

    }
    </script>
</head>
<body>
    <form>
        <select name="list" id="list" size="3" multiple="multiple">
            <option value="India">India</option>
            <option value="US">US</option>
            <option value="Germany">Germany</option>
        </select>
        <input type="text" id="str" name="str" />
        <br /><br />
        <input type="button" id="chk" value="make a string!" name="chk" onclick="list_to_string();"/>
    </form>
</body>
</html>

最佳答案

字符串连接在 IE 上非常慢,请改用数组:

function listBoxToString(listBox,all) {
    if (typeof listBox === "string") {
        listBox = document.getElementById(listBox);
    }
    if (!(listBox || listBox.options)) {
        throw Error("No options");
    }
    var options=[],opt;
    for (var i=0, l=listBox.options.length; i < l; ++i) {
        opt = listBox.options[i];
        if (all || opt.selected ) {
            options.push(opt.value);
        }
    }
    return options.join(",");
}

关于javascript - 使用 Javascript 从 HTML 列表框(多选)中的项目生成逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/544936/

相关文章:

javascript - 如何使用python获取链接内元素的文本

javascript - dgrid - 可编辑字段之间的键选项卡导航

javascript - 使用 jquery 将 Html 转换为搜索文本

javascript - Highcharts 列 : add dynamically series with drilldown data

javascript - 如何创建 Dropbox 托管应用程序

javascript - Javascript 中的字符串比较

javascript - 是否有一个 UI 框架来模拟 Mac 应用程序的外观?

html - 如何在导航栏中将 <img> 放置在两个 <ul> 之间?

Java URL 文本文件转字符串

java - 查找给定两个字符串的所有公共(public)子字符串