Download Javascript Array on a Combobox

Asked

Viewed 1,092 times

4

I would like help in this small problem, I have to do a combobox shows 5 states being loaded by an array in javascript, my code is like this.

HTML

<select >
    <option id="estado"></option>
</select>

My Javascript is like this

var select = document.getElementById("estado"); 
var options = ["São Paulo", "Rio de Janeiro", "Paraná", "Pernambuco", "Rio Grande do Sul"]; 

    for(var i = 0; i < options.length; i++) {
        var opt = options[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        //console.log(el);
        select.appendChild(el);
    }

Debugging in the console.log brings the cute results as it should be. But when printing the object it brings the following error.

Uncaught Typeerror: Cannot read Property 'appendchild' of null.

1 answer

4


The id should be on select and not in the option.

Anyway the current code should not present the error that you showed, this seems more a problem with the order of things, IE, check if it is not calling the script before the creation of the elements, this is a common mistake.

var select = document.getElementById("estado"); 
var options = ["São Paulo", "Rio de Janeiro", "Paraná", "Pernambuco", "Rio Grande do Sul"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    
    select.appendChild(el);
}
<select id="estado">
    <option></option>
</select>

  • So I ran here in the stack and it worked but in my code remains the same error, that thing.

  • Then there should be no element with id estado.

  • Found the problem @Alisonpaulo?

  • So I think so, but I’m not finding a way to solve it. For example html and js are separated, ids are equal, what I think html is not doing the request, I do not know if I have to do some event to send id to js

  • That doesn’t make much sense. Or I got it all wrong.

  • Javascript is not running tapirs of the creation of the elements, right? This may be the problem.

  • look at the codes are exactly like your answer, if I debug with cosole.log without printar select.appendchild(el); it shows the 5 states, but when printo select.appendchild(el); it gives the error. That’s what I don’t understand.

  • Javascript is not running before HTML creation?

  • That’s right, that drug I lost 2 hours atoa. I was making the call in the head, I changed the location of the call worked out. Vlw ai brother thanks even.

  • there is some difference in using . appendchild or . add?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.