Duplicating/Cloning Multiple Form Fields

Not sure what to call this one, but I am working on a form that asks for product information (name, description, color, features, etc.) but what I’d like to do is give users the option to add additional products by clicking on a link. They could add as many products as they need. After they finish entering information they could click a link that states "Add another product" or something similar and the form would give them a whole set of new fields that they could fill out. Through the same form, the page would grow as the items are added and it would be part of the same form (instead of having to submit the form over and over again on a per-product basis).

I hope I’m making sense, does anyone know what the term is for this or have any recommendations on a plugin that could do something like this? Magic fields can do this but on the back-end not the front-end.

enter image description here

1 Answer
1

Instead of looking for a plugin I found a piece of code that solves my problem, unfortunately because I am not using a plugin this post doesn’t relate to WordPress and is off-topic. For those of you who are curious the code I am using is at:
http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#btnAdd').click(function() {
                var num     = $('.clonedInput').length;
                var newNum  = new Number(num + 1);

                var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);

                newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
                $('#input' + num).after(newElem);
                $('#btnDel').attr('disabled','');

            if (newNum == 5)
                $('#btnAdd').attr('disabled','disabled');
        });

        $('#btnDel').click(function() {
            var num = $('.clonedInput').length;

            $('#input' + num).remove();
            $('#btnAdd').attr('disabled','');

            if (num-1 == 1)
                $('#btnDel').attr('disabled','disabled');
        });

        $('#btnDel').attr('disabled','disabled');
    });
    </script>
</head>

    <body>
        <form id="myForm">
            <div id="input1" class="clonedInput">
                Name: <input type="text" name="name1" id="name1" />
            </div>

            <div>
                <input type="button" id="btnAdd" value="add another name" />
                <input type="button" id="btnDel" value="remove name" />
            </div>
        </form>
    </body>
</html>

Leave a Comment