简体   繁体   中英

Bootstrap form dynamically add remove form with fields

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, ie 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:

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.

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();
        });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM