Repeating div with form fields

后端 未结 3 756
谎友^
谎友^ 2020-12-16 08:41

I have a form where I want to be able to duplicate a group of fields as many times as I want. And I also want to have field id, name, and label\'s

3条回答
  •  [愿得一人]
    2020-12-16 09:00

    This should automatically rename according all three elements:

    // Add a new repeating section
    $('.addFight').click(function(){
        var currentCount =  $('.repeatingSection').length;
        var newCount = currentCount+1;
        var lastRepeatingGroup = $('.repeatingSection').last();
        var newSection = lastRepeatingGroup.clone();
        newSection.insertAfter(lastRepeatingGroup);
        newSection.find("input").each(function (index, input) {
            input.id = input.id.replace("_" + currentCount, "_" + newCount);
            input.name = input.name.replace("_" + currentCount, "_" + newCount);
        });
        newSection.find("label").each(function (index, label) {
            var l = $(label);
            l.attr('for', l.attr('for').replace("_" + currentCount, "_" + newCount));
        });
        return false;
    });
    
    // Delete a repeating section
    $('.deleteFight').live('click',function(){
        $(this).parent('div').remove();
        return false;
    });​
    

    I changed the delete handler, to use .live() instead, so that the handler would also be attached to newly created copies of that button. Now, if you're using jquery > 1.7 you should use .on()

    The on() version would be:

    // Delete a repeating section
    $(document).on('click','.deleteFight',function(){
        $(this).parent('div').remove();
        return false;
    });
    

提交回复
热议问题