1

I have a Bootstrap horizontal form (with many fields) and would like functionality to add/remove one or many "sub-forms (with many fields) to the parent form.

Also I'm not sure which path to go down, i.e. code with Bootstrap components, or purely with jQuery and CSS (within Bootstrap), or JavaScript only (within Bootstrap).

This may be a simple question, and I've been searching for a bread and butter solution, but with no luck. Perhaps it's very difficult to do.

Found this, but no help Similar question on SO

And this, but it's done in JavaScript Another question on SO

Here is an example of what I'd like to do, I have a parent form which contains personal details fields, and would like when a user clicks a button (+) an address form is dynamically added, and if button (-) is clicked, the address form is removed.

Person

Firstname:

Surname:

Email:

Button (+/-)


Address 1

Street:

Suburb:

Postcode:


Address 2

Street:

Suburb:

Postcode:

2 Answers 2

1

I've done something like you are talking about with Kendo. Basically, you need a template and add/remove item capability. Using any templating capability, you can define a template, and dynamically generate the template based on a JSON object, and add it to the DOM tree, or remove an existing item from the DOM tree with jQuery.

Sign up to request clarification or add additional context in comments.

Comments

1

A template is a great option and probably the way you should go. However, if you want to avoid adding a templating engine, you can do it with jQuery, or even just vanilla JS.

Here is simple JQuery example:

  $(function () {
    function createGroup(name) {
        var label = document.createElement("label");
        $label = $(label);
        $label.attr("for", name)
            .text(name);

        var input = document.createElement("input");
        $input = $(input);
        $input.addClass("form-control")
            .attr("type", "text")
            .attr("name", name);

        var group = document.createElement("div");
        $group = $(group);
        $group.addClass("form-group")
            .append(label, input);

        return group;
    }

    $("#plusButton").click(
        function () {
            var newHorizontalForm = document.createElement("div");
            $(newHorizontalForm).append(createGroup("New Input"),
                    createGroup("New Input"),
                    createGroup("New Input"))
                .addClass("form-horizontal");
                $("#form").append(newHorizontalForm);
    });


     $("#minusButton").click(
            this.parent.remove();
        });

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.