1

I am trying to make a combobox in javascript and populate it from an array. On selection I want to change a variable, 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

0

1 Answer 1

6
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);
Sign up to request clarification or add additional context in comments.

6 Comments

Again thanks DaveRandom this is perfect. I just have one remaining question; I notice you have to have an element in the HTML page already defined (I used a div) to append the comboBox. Is there any way of dynamically making this element within the javascript?
@r34ch you can make as much of an element hierarchy as you want, but you always have to have a parent element to add it to. I will update the answer so it creates a <div> to contain the <select>, but then what are you going to add the <div> to? You need to something statically defined on the page to get a reference to and call appendChild() on it.
Also a minor correction for anyone else; alert('You selected option '+this.selectIndex); should read; alert('You selected option '+this.selectedIndex);
Ahhh then my mistake, I did not know an element must be present in the HTML to append. I thought naively you could append to the body. Anyway your answer is working nicely, many thanks.
You can do document.body.appendChild(); but surely your page must have some content already? And cheers for pointing out that error, I have fixed it above.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.