Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript?:How to dynamically add text inputs/form fields to a HTML form?

I am building a web form where there is a list of inputs. So far, so good.

However, how can I add a link/button to add say another 5 fields to the list. eg:

<input>
<input>
<input>
<input>

<a href="" onclick="">Add 10 more fields</a>

I have looked through many similar q's on this site, however none seem to describe how to add multiple fields.

Thanks for any help,

Harley

EDIT: Thanks all for help, looks like jquery append is the way to go. However I appreciate the alternative that does not use jquery.

like image 517
harley_woop Avatar asked Jul 13 '12 16:07

harley_woop


4 Answers

  $("#anyDiv").html('<input id="id1"/>');

....

 $("#anyDiv").append('<input id="id2"/>');
like image 77
Suave Nti Avatar answered Sep 23 '22 19:09

Suave Nti


Here's a js fiddle showing the example of adding 10 inputs using jQuery's append() function. I suggest only doing one addition per click as in user1301840's example though.

HTML

<div id="inputList"></div>
<input type="button" value="Add 10 Inputs" id="addInputs" />​

Javascript

$('#addInputs').click(function() {
    for (i = 0; i < 10; i++) {
        $('#inputList').append('<input type="text" />');

    }
});​
like image 35
Jerry Avatar answered Sep 22 '22 19:09

Jerry


While you already have answers, I thought I'd try and provide a non-jQuery solution:

function addInput(insertAt, formEl, num, inputType, defaultVal) {
    console.log(formEl);
    if (!formEl) {
        return false;
    }
    else {
        num = num ? num : 5;
        var fieldset = document.createElement('fieldset'),
            newInput;
        for (var i = 0; i < num; i++) {
            newInput = document.createElement('input');
            newInput.value = defaultVal || '';
            newInput.type = inputType || 'text';
            fieldset.appendChild(newInput);
        }
        formEl.insertBefore(fieldset, insertAt);
    }
}

var formEl = document.getElementById('theForm'),
    aElem = document.getElementById('aElement');

if (window.addEventListener) {
    // up to date browsers
    aElement.addEventListener('click', function() {
        addInput(this, formEl, 10);
    }, false);
} else if (window.attachEvent) {
    // legacy IE, <9
    aElement.attachEvent('onclick', function() {
        addInput(this, formEl);
    });
}​

JS Fiddle demo.

I don't have IE to test, but the above should work with IE < 9 using the attachEvent fall-back, and >= 9, I think, implements the standard addEventListener().

References:

  • addEventListener().
  • attachEvent().
  • document.createElement().
  • insertBefore().
like image 20
David Thomas Avatar answered Sep 23 '22 19:09

David Thomas


try use the JQuery .append() function

$("a").click(function(e){
 $("form").append("<input />");
})
like image 35
lusketeer Avatar answered Sep 22 '22 19:09

lusketeer