Streaming live at 10am (PST)

Add input fields dynamically to forms

I have a form that has a field like Add item n number of times (depends on user).

How could I achieve this?


2 Likes

@Oscar_A_Montiel

Hi Oscar

Did you mange to complete this in Webflow at all?

I’m looking to do something similar at the moment.

Many thanks

I did it with JavaScript. I don’t remember the code, but it was easy to do.

you can add an event listener into page body custom code

document.getElementById("myButton").addEventListener("click", addFields);

give the button the id “myButton” in webflow

Then back in page body custom code you can write a function ‘addField’ that adds the fields where you want to. Something like this:

<script type='text/javascript'>
    function addFields(){
        // Number of inputs to create
        var number = document.getElementById("amountToAdd").value;
        // Container <div> where dynamic content will be placed
        var container = document.getElementById("container");

        for (i=0;i<number;i++){
            // Append a node with a random text
            container.appendChild(document.createTextNode("Label text"));
            // Create an <input> element, set its type and name attributes
            var input = document.createElement("input");
            input.type = "text";
            input.name = "addedfield_" + i;
            container.appendChild(input);
            // Append a line break 
            container.appendChild(document.createElement("br"));
        }
    }
</script>