Dynamic combobox javascript
I am trying to make a combobox in javascript and populate it from an array. On selection I want to change a 开发者_StackOverflowvariable, call a function etc. I have looked at multiple tutorials on-line but for such an easy task the tutorials are dire.
Can anyone help? Cheers
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theOptions = ['option 1','option 2','option 3'];
// Create the container <div>
theContainer = document.createElement('div');
theContainer.id = 'my_new_div';
// Create the <select>
theSelect = document.createElement('select');
// Give the <select> some attributes
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.className = 'class_of_select';
// Define something to do onChange
theSelect.onchange = function () {
// Do whatever you want to do when the select changes
alert('You selected option '+this.selectedIndex);
};
// Add some <option>s
numOptions = theOptions.length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = i;
anOption.innerHTML = theOptions[i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);
精彩评论