115

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.

My HTML Code:

<input type="text" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails">Fill Details</a>

So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.

I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
xan
  • 4,640
  • 13
  • 50
  • 83

2 Answers2

181

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Generate a dynamic number of inputs
            var number = document.getElementById("member").value;
            // Get the element where the inputs will be added to
            var container = document.getElementById("container");
            // Remove every children it had before
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>

See a working sample in this JSFiddle.

Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • I followed your advice. But when I click on, the browser console shows this error: `Uncaught TypeError: Cannot call method 'appendChild' of undefined ` – xan Feb 13 '13 at 12:55
  • The answer so much helpful. And how can I add a CSS class to the field – Pravinraj Venkatachalam Jul 13 '17 at 07:14
  • 4
    @Pravin Glad it helped, see [How do I add a class to a given element?](https://stackoverflow.com/q/507138/851811). Basically use `input.className += ' someCSSClass';` – Xavi López Jul 13 '17 at 08:10
  • 1
    When I submit the form, the new fields generated dynamically are not submitted like the other fields that were part of the original HTML. They show up visually and I can inspect them but they don't submit. Any ideas why that would happen? – circle1 Jul 27 '18 at 15:45
  • 1
    @circle1 Make sure the dynamically generated elements do have a unique `name` attribute. Only form elements with a name attribute will have their values passed when submitting a form. – Xavi López Jul 27 '18 at 19:06
  • @Xavi López I did check that first thing and they do have a valid and unique name attribute. If I take the HTML appended by the javaScript and have it load as part of the original HTML, they work fine, but when they are added on the fly by JS they won't submit. – circle1 Jul 28 '18 at 20:16
  • I just created small project to test whether dynamically added input with name will get submitted using C# MVC. It worked fine. Not sure what framework you were using, but perhaps your model was missing property with the same name as "name" attribute? – Vanity Slug - codidact.com Dec 27 '18 at 15:03
  • @AGrush well, it still does for me. What exactly do you find that is not working? – Xavi López Jan 02 '20 at 01:25
  • sorry it does figured it out thanks, had to put a number in the input – AGrush Jan 02 '20 at 15:26
53

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

$(document).ready(function() {
    var max_fields = 10;
    var wrapper = $(".container1");
    var add_button = $(".add_form_field");

    var x = 1;
    $(add_button).click(function(e) {
        e.preventDefault();
        if (x < max_fields) {
            x++;
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
        } else {
            alert('You Reached the limits')
        }
    });

    $(wrapper).on("click", ".delete", function(e) {
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
    <button class="add_form_field">Add New Field &nbsp; 
      <span style="font-size:16px; font-weight:bold;">+ </span>
    </button>
    <div><input type="text" name="mytext[]"></div>
</div>
Zoe
  • 27,060
  • 21
  • 118
  • 148
M. Lak
  • 903
  • 9
  • 18
  • Maybe I'm doing something wrong, but in my case any pressing enter in a text field in this form will lead to the 'Add New Field' button's function being fired, which is probably unwanted behavior... – Maxi Mus Sep 08 '20 at 21:10
  • 2
    ` – Maxi Mus Sep 08 '20 at 21:18
  • Hello! When I go to save the data of the dynamic inputs, how do I recover them all? – Hector Echeverri Feb 18 '21 at 15:43
  • Good answer. plus+. BUT... vanilla javascript ?? Some people dislike adding libraries. – James Walker Jun 05 '22 at 19:35
  • @M. Lak let's suppose we increase the input element by `1` on each `click` event and these `fields` values are submitted with `form` how can we retrieve each `input` field `values` can you please update the answer so that each `input` field will have dynamic (unique) `id` or `name` attr – Azhar Uddin Sheikh Aug 19 '22 at 12:42
  • Also how can we **validate** such `form` using `jquery` – Azhar Uddin Sheikh Aug 19 '22 at 12:57