Bind the html select control from the comma separated string in JavaScript

The following code sample demonstrates how to bind the select control from the comma delimited string. The example contains a commas separated string, form which we will create the option elements of the select element

You will see in the code below, we convert the comma separated string to an array object using the split method. Then we create the options from this array.

Demo

Enter the comma separated string in the textbox and click on the button.

Enter the comma separated string:



Example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head runat="server">
    <title>Example of the HTML5 color input tag</title>
 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script type="text/javascript">
        $(document).ready(function() {
            $("#btnClick").click(function() {
                var str = "NewDelhi,Londan,NewYork";
                var arr = str.split(",");
                $(arr).each(function() {
                    $('#selectElem').append($("<option>").attr('value', this).text(this));
                });
            });
        });
    </script>
 
</head>
<body>
    <form id="form1" runat="server">
    <select id='selectElem' style="width:150px">
    </select>
    <input type="button" id="btnClick" value="Click Here" />
    </form>
</body>
</html>

If you don't want to use the jQuery than you can use the following code in JavaScript:

 
var str = "NewDelhi,NewYork,londan";
var arr = str.split(",");
 
select = document.getElementById('selectElem');
for (var i = 0; i < arr.length; i++) {
      var opt = document.createElement('option');
      opt.value = arr[i];
      opt.innerHTML = arr[i];
      select.appendChild(opt);
}