1

I am using javascript to populate a select box in my page but its not working, the select box displays but its completely empty.

I also get no error in my console.

My script is this:

        var select = document.createElement("select");
            for(var i in resource){
                if(i !== id && select.hasOwnProperty(i)){
                    select.setAttribute(i, resource[i].name);
                }
            }
            d.appendChild(select);

Example data for resource:

{
 "1":{"name":"Test"},
 "2":{"name":"Test2"},
 "3":{"name":"Test3"}
}

Any ideas on why it won't populate?

5
  • 1
    What are you expecting that to do? If you want those to be options in your drop-down you have to create option elements? What do 'name' and 'type' correspond to? Commented May 7, 2013 at 2:43
  • Those are just object properties I'm using to populate the select box. Well not type - ignore that property of the object. Commented May 7, 2013 at 2:44
  • 1
    OK, but what do they correspond to in terms of your drop-down. Is 'name' the text which is displayed for each option in the list? Commented May 7, 2013 at 2:45
  • Yes and the the i will be the object such as resource[1] etc Commented May 7, 2013 at 2:45
  • Thats what i thought setAttribute was meant to do any way. Commented May 7, 2013 at 2:48

2 Answers 2

8

There are quite few mistakes in your script, many are mentioned in the comments as you can see.

What you are looking for might be something like this

var select = document.createElement("select");
for(var i in resource){
    if(resource.hasOwnProperty(i)){ //removed the i !== id condition, you may put it back
        var opt = new Option(resource[i].name, i);
        select.options[select.options.length] = opt;
    }
}
document.body.appendChild(select);

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

17 Comments

this must be a typo i guess.. opt should be Option(resource[i].name, i) first parameter is for text and second for value!
@razzak yes, in the fiddle it was corrected forgot to copy here
Ah i see so when does setAttribute get used for anything ?
Should also mention shouldn't resource.hasOwnProperty(i) be !resource.hasOwnProperty(i)
@ArunPJohny if it has its own property then it should skip rather than make it again surely?
|
1

You need to create child elements of the select, that are option tags.

Here's a sample JSFiddle.

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.