开发者

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜