Data Binding a Select Element

How to use the each function in jQuery to bind a select element to an array of JavaScript objects.

by Rich Costello

HTML

<select id="dataBoundSelect">
</select>

JavaScript

// the select element will be data bound to this array of objects
var options = [
    {text: "Uno", value: 1},
    {text: "Dos", value: 2},
    {text: "Tres", value: 3},
    {text: "Cuatro", value: 4},
    {text: "Cinco", value: 5}
];

// initialize jQuery
$(function() {
    // get a jQuery wrapper around the select element
    var dataBoundSelect = $("#dataBoundSelect");
    
    // iterate over the options array
    // i is the current index, e is the current value in the array
    $(options).each(function(i, e) {
        // create a new option element
        // set the html to the text of the text property in the current object
        // set the value attribute the to the value property
        var option = $("<option>").html(e.text).attr("value", e.value.toString());
        // add the option to the end of the select element
        dataBoundSelect.append(option);
    });
});