0

I'm making a JS application that automatically another textbox on user input. I'm not however sure how I append an input to a li

The end result I want to get at is this:

<ul id="lst">
  <li>Item1: <input type="text"></li>
  <li>Item2: <input type="text"></li>
  <!-- more li added on button press -->
</ul>

what I got so far is this:

var onClick = function() {
  var ul = document.getElementById('lst'),
      li = document.createElement('li');
  li.appendChild(document.createTextNode('Item' + counter + ': '));
  counter++;
  ul.appendChild(li);
}

How do I also append the <input type="text"> node?

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
  • I think this is what you are looking for: http://stackoverflow.com/a/5656401/4298881. Construct a input node and append it after you append the Item – Surely Aug 19 '15 at 17:23

2 Answers2

1

The same way you added the text to the element.

var onClick = function() {
  var ul = document.getElementById('lst'),
      li = document.createElement('li'),
      input = document.createElement('input');
  input.type="text";
  li.appendChild(document.createTextNode('Item' + counter + ': '));
  li.appendChild(input);
  counter++;
  ul.appendChild(li);
}
Schleis
  • 41,516
  • 7
  • 68
  • 87
0

It's probably easier to use a label element as well, and append that along with an input

var onClick = function() {
    var ul    = document.getElementById('lst'),
        li    = document.createElement('li'),
        label = document.createElement('label'),
        input = document.createElement('input');

    label.text = "Item " + counter + ":";
    li.appendChild(label);
    //input.type = "text";
    li.appendChild(input); //defaults to type text
    ul.appendChild(li);

    counter++;
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157