views:

1559

answers:

3

So if you have a html List Box, also called a multiple select, and you want to generate a comma delimited string that lists all the values in that List Box you can you can do that with the following example. The list_to_string() js function is the only important thing here. You can play with this page at 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>
A: 

I answered this in the original post.

Gourneau
+1  A: 

You could use array.join(','); to create a comma separated list from an array.

Something like this, only better:

var list_to_string = function() {
    var opts = document.getElementById('list').options;
    var i = 0, len = opts.length, a = [];
    for (i; i<len; i++) {
        a.push(opts[i].value);
    }
    document.getElementById('str').value = a.join(',');
}
shiftins
hasOwnProperty is non-portable; use a normal `for (var i= 0; i<opts.length; i++)` loop in preference.
bobince
+2  A: 

String concatenation is very slow on IE, use an array instead:

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(",");
}
some