Use jquery to build a new list

Interesting use of jquery to build a list http://www.electrictoolbox.com/jquery-add-option-select-jquery/

by Andy Bulka

HTML

<select id="example" size="10" style="width: 15em">

JavaScript

$(function () {
    // Interesting use of jquery to build a list - http://www.electrictoolbox.com/jquery-add-option-select-jquery/                                       
    var newOptions = {
        'red' : 'Red',
        'blue' : 'Blue',
        'green' : 'Green',
        'yellow' : 'Yellow'
    };
    var selectedOption = 'green';
    
    var select = $('#example');
    if(select.prop) {
      var options = select.prop('options');
    }
    else {
      var options = select.attr('options');
    }
    $('option', select).remove();
    
    $.each(newOptions, function(val, text) {
        options[options.length] = new Option(text, val);
    });
    select.val(selectedOption);

});