Erick
Erick

Reputation: 1

Dynamically add a select dropdown menu in javascript

I'm trying to add a dropdown menu and other input fields dynamically. So far it works fine adding Text input field, but it does nothing with Select input (dropdown).

This is the HTML:

<form method="POST"> 
    <div id="dynamicInput"></div>
    <input type="button" onClick="addInput('dynamicInput');" value="Add inputs"/>
</form>

This is the Javascript:

function addInput(divName){
    var newdiv = document.createElement('div');
    newdiv.innerHTML = 
   "<input type='text' id='name'>"+
   '<select id="age">
       <option value="18">18</option>
       <option value="18">18</option>
   </select>';
   document.getElementById(divName).appendChild(newdiv);
}

Peace.

Upvotes: 0

Views: 480

Answers (1)

msfoster
msfoster

Reputation: 2572

I bet your console tells you something like unexpected token. Concatenation of a multiline string requires escaping.

You can do:

myVar = "hello \
    sir!";

or concatenate each line:

myVar = "hello " + 
    "sir!";

Upvotes: 1

Related Questions