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.


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

Enter the comma separated string:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<head runat="server">
    <title>Example of the HTML5 color input tag</title>
    <script type="text/javascript" src=""></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));
    <form id="form1" runat="server">
    <select id='selectElem' style="width:150px">
    <input type="button" id="btnClick" value="Click Here" />

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];