Javascript – How to add textbox dynamically

clonejavascriptPHP

Help with this criteria ?

Users can be able to add as many Names as they want, ADD NAME link serves the purpose for this.

How can I handle this specification ?
Please check the spec below:

alt text

Thanks.

Best Answer

var input = $('#input').clone().attr('name', 'name2').attr('id', 'input-2').appendTo('body')

You can go further and clone the entire row/div with $(el).clone() and then do .find('input') and modify the name and id attribute values so they're unique and don't conflict. You can pass true to clone if you want to copy the event handlers.

Incomplete non-jQuery "solution" since I don't know exactly at which point the OP is in since he claims he can clone nodes now..

  <div id="wrap">
    <div class="foo">
      <label for="first_name">name:</label><input type="text" name="first_name[]  " id="first_name"><a href="#">delete</a>
    </div>
    <a href="#" id="add">add name</a>
  </div>
  <script>
  (function() {
    var add = document.getElementById('add'), counter = 0;
    add.onclick = function() {
      var rows = document.getElementsByTagName('div'), last = false;
      if ( rows.length ) {
        for ( var i = rows.length; i--; ) {
            if ( last ) { break; }
            if ( rows[i].className.length && ( ' ' + rows[i].className + ' ' ).indexOf(' foo ') != -1 ) {
              last = rows[i];
            }
        }
      }
      if ( last ) {
        var newNode = last.cloneNode(true), wrap = document.getElementById('wrap'), input = newNode.getElementsByTagName('input');
        input.id = input.id + (counter++);
        wrap.appendChild( newNode );
      }
    }
  })();