Using jQuery to dynamically add form fields (or fieldsets) based on a dropdown box value

前端 未结 2 544
萌比男神i
萌比男神i 2020-12-17 03:34

As the title says, what I am trying to do is to have jQuery add a number of extra fieldsets based on the value selected in a drop-down box. For example, when the page loads,

相关标签:
2条回答
  • 2020-12-17 04:02

    Why are you cloning instead of just doing something like this (together with your current event listener)?

    $(".divWhereTheseGo").empty();
    var count = 0;
    while (count < maxItems) {
       $(".divWhereTheseGo").append("<fieldset id=\"" + count + "\">your form info</fieldset>");
       count++;
    }
    

    The count in the fieldset is how you can handle the unique id issue.

    0 讨论(0)
  • 2020-12-17 04:05

    I don't like the solution of Nate B.

    • it needs an additional container element
    • recreates everything, thus loosing data already entered
    • creates a maintenance problem: html markup of the fieldset is duplicated (once in HTML, once as string for append)
    • creates invalid id's for the fieldsets (id's can't start with a number)

    This does what you want and similar to what you did. Keeps only the ids in a data attribute on the original element (instead of keeping the whole clone object which could use massive amounts of memory). Keeps all values already entered. Doesn't recreate everything if you change from e.g. 3 to 5. Instead only generates two new fieldsets. Removes them in reverse order they where created.

    jQuery.fn.fieldsManage = function (number) {
        var ele = $(this);
        var clones = ele.data("clones");
        clones = clones ? clones : new Array(ele.attr("id"));
        if (clones.length < number) {
            var clone;
            while(clones.length < number) {
                clone = ele.clone(true);
                var id = clones[0]+clones.length;
                clone.attr("id", id);
                $("#"+clones[clones.length-1]).after(clone);
                clones.push(id);
            }
        } else {
            while(clones.length > number) {
                $("#"+clones.pop()).remove();
            }
        }
        ele.data("clones", clones);
    }
    
    $(document).ready(function() {
        $("#itemCount").change(function() {
            $("#item_dup_1").fieldsManage(this.value);
        });
    });
    
    0 讨论(0)
提交回复
热议问题