Lemex
Lemex

Reputation: 3804

Javascript InnerHTML Output Wrong

function test()
{
var formHTML ="";
var frmid ="test123";

var options = ["Test1", "Test2", "Test3", "Test4", "Test5"]
formHTML += "<select id='" + frmid + ">";

console.log(options);

for ( i = 0; i < options.length; i++) {
    var temp = options[i];
    var temp2 = "<option value='" + temp + "'>" + temp + "</option>";
    console.log(temp2);
    formHTML += temp2;
}
formHTML += "</select>";
console.log(formHTML); 
document.getElementById("injected").innerHTML+=formHTML;

}

Above is my function to make a select element in my page, when i call this function there is a very strange issue, it only dispalys options test2,test3,test4,test5 and not one...

When i print out formHTML using console.log it shows..

<select id='test123><option value='Test1'>Test1</option>
<option value='Test2'>Test2</option>
<option value='Test3'>Test3</option>
<option value='Test4'>Test4</option>
<option value='Test5'>Test5</option>
</select> 

But if you run the code and look at the source code the HTML element is not correct the first element looks like

 <option value='test1'> Test1

Missing the close option tag,

I have tried debugging and changing code around but this issue has left me confused.

Is there something missing is there better way of going about this? I am trying to store it all in one string before manipulating the DOM for speed reasons. All help is appreciated, Thanks

Upvotes: -1

Views: 1061

Answers (1)

coolguy
coolguy

Reputation: 7954

YOu have an error in this line

formHTML += "<select id='" + frmid + ">";

Change that to

formHTML += "<select id='" + frmid + "'>";

Upvotes: 4

Related Questions