Create a comma delimited string from elements in an HTML list box (multiple choices) using Javascript

So, if you have an html List Box, also called multiple selection, and you want to generate a comma-delimited string that lists all the values ​​in this list box, you can do this with the following example. The list_to_string () js function is important 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> 
+4
source share
3 answers

String consolidation is very slow in 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(","); } 
+4
source

You can 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(','); } 
+1
source

This can also be simply done using Request.Form(control.UniqueID) to pull out the already defined comma separated values ​​that are already present for the multitask list.

+1
source

All Articles