Clone form and increment

前端 未结 5 421
感情败类
感情败类 2020-12-03 16:21

I have a form below that I want to clone, increment the id(att1) and it\'s inputs, textareas etc and append to the attendees div. Any help much appreciated. Been wrecking my

5条回答
  •  春和景丽
    2020-12-03 17:11

    See the fiddle.

    Add a class attendee to the div id="att1"

     

    And the JS:

    $(function(){
        var template = $('#attendees .attendee:first').clone(),
            attendeesCount = 1;
    
        var addAttendee = function(){
            attendeesCount++;
            var attendee = template.clone().find(':input').each(function(){
                var newId = this.id.substring(0, this.id.length-1) + attendeesCount;
                $(this).prev().attr('for', newId); // update label for (assume prev sib is label)
                this.name = this.id = newId; // update id and name (assume the same)
            }).end() // back to .attendee
            .attr('id', 'att' + attendeesCount) // update attendee id
            .prependTo('#attendees'); // add to container
        };
    
        $('.add').click(addAttendee); // attach event
    });
    

提交回复
热议问题