0

i want to dynamically add options to drop down boxes

  var x =document.getElementById("c");
    var optn = document.createElement("OPTION");
    optn.text="hhh"
    optn.value="val"
    x.options.add(optn);

I am doing it inside a loop,with diff values of for val and hhh.Bur sometime i dont see any any values in drop down box , what may be the problem?

0

3 Answers 3

0

Try this one:

var objSelect = document.getElementById("subComponentOSID");
objSelect.options[objSelect.options.length] = new Option('1','1');
objSelect.options[objSelect.options.length] = new Option('2','2');
Sign up to request clarification or add additional context in comments.

Comments

0

add is a method of HTMLSelectElement objects, not of HTMLCollection objects.

x.add(optn)

Comments

0

Assuming the element with the id "subComponentOSID", the only apparent issues in your javascript are missing semicolons on the lines where you assign values to optn.text and optn.value. Also, while most browsers will resolve what you mean when calling the add function on an options collection for a select element, you should move your add to the select itself. See the Mozilla reference for HTMLSelectElement, which provides an example.

In the meantime, try replacing the code snippet you provided with this:

var x =document.getElementById("subComponentOSID");
var optn = document.createElement("OPTION");
optn.text="hhh";  //Added semi-colon
optn.value="val";  //Added semi-colon
x.add(optn);  // Moved add to HTMLSelectElement

Comments

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.