How to bind <select> from list of comma separated values in JQuery?

Abhishek B. picture Abhishek B. · Aug 19, 2011 · Viewed 10k times · Source

How we can bind select tag with variable data?..

Here is my sample code here.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script>
var google.language.Languages = {
  'AFRIKAANS' : 'af',
  'ALBANIAN' : 'sq',
  'AMHARIC' : 'am',
  'ARABIC' : 'ar',
  'ARMENIAN' : 'hy',
  'AZERBAIJANI' : 'az' ...
}
</script>

I want Bind my select tag using above languages

<select id="langsel" name="selector">
        <option value="">Select a language</option>
</select>

How to bind "langsel" select with above variable.?

I need output like below :

 <select id="langsel" name="selector">
            <option value="">Select a language</option>
            <option value="af">AFRIKAANS</option> 
            ....
    </select>

Answer

daryl picture daryl · Aug 19, 2011
$(function() {

    var languages = {
      'AFRIKAANS' : 'af',
      'ALBANIAN' : 'sq',
      'AMHARIC' : 'am',
      'ARABIC' : 'ar',
      'ARMENIAN' : 'hy',
      'AZERBAIJANI' : 'az'
    }

    var sel = $('#langsel');

    $.each(languages, function(key, value) { 
        sel.append('<option value="'+value+'">'+key+'</option>');
    });

});

Working Fiddle: http://jsfiddle.net/qtb6S/