Dynamic select options

by larsolesimonsen

HTML

<select>
</select>
<br/>
<input type="button" id="bn1" value='foo'/>
<br/>
<input type="button" id="bn2" value='bar'/>
<br/>
<input type="button" id="bn3" value='foo + bar'/>

JavaScript

var options = [{id:'foo', opts: ['foo1','foo2','foo3']},
               {id:'bar', opts: ['bar1','bar2','bar3']}];

$('input#bn1').click(function() {
    var optionsHtml;
    for(i = 0; i < options[0].opts.length; i++) {
        optionsHtml = optionsHtml + '<option>' + options[0].opts[i] + '</option>'
    }
    $('select').html(optionsHtml);
});

$('input#bn2').click(function() {
    var optionsHtml;
    for(i = 0; i < options[1].opts.length; i++) {
        optionsHtml = optionsHtml + '<option>' + options[1].opts[i] + '</option>'
    }
    $('select').html(optionsHtml);
});

$('input#bn3').click(function() {
    var optionsHtml;
    for(j = 0; j < options.length; j++) {
        for(i = 0; i < options[j].opts.length; i++) {
            optionsHtml = optionsHtml + '<option>' + options[j].opts[i] + '</option>'
        }
    }
    $('select').html(optionsHtml);
});