Creating options with data values
by David Buzatto
HTML
<select id="mySelect">
<option>Make a choice!</option>
</select>
JavaScript
var select = document.getElementById( "mySelect" );
select.add( createOption( "a", "1", { add1: "foo1", add2: "bar1" } ) );
select.add( createOption( "b", "2", { add1: "foo2", add2: "bar2" } ) );
select.add( createOption( "c", "3", { add1: "fruit", add2: "loop" } ) );
select.add( createOption( "d", "4" ) );
select.add( createOption( "e", "5", { add1: "none", add2: "john doe" } ) );
select.onchange = function(evt) {
var allData = "";
var option = evt.target.options[evt.target.selectedIndex];
allData += option.innerHTML;
allData += " value: " + option.value;
for ( d in option.dataset ) {
allData += "\n " + d + ": " + option.dataset[d];
}
alert( allData );
};
function createOption( text, value, data ) {
var newOpt = document.createElement( "option" );
newOpt.innerHTML = text;
newOpt.value = value
for ( d in data ) {
newOpt.dataset[d] = data[d];
}
return newOpt;
}