我下面有一个表格,我想要克隆,增加id(att1)及其输入,文本区域等,然后追加到与会者div。任何帮助,不胜感激。伤了我的头...
我只有...
$(function () {
var index = 1;
$(".add").click(function () {
index++;
$("#att1").clone(true).removeAttr("id").attr("id", "att" + index).appendTo("#attendees");
alert(index);
});
});
HTML:
<div id="attendees">
<div id="att1">
<fieldset>
<legend><span class="legend">Attendee 1 Booking Details</span></legend>
<p name="test">
<label for="A_Title_1">Title: <span class="req">*</span></label>
<input name="A_Title_1" id="A_Title_1" value="" type="text" class="f_input" />
</p>
<p>
<label for="A_Forename_1">Forename: <span class="req">*</span></label>
<input name="A_Forename_1" id="A_Forename_1" type="text" class="f_input" />
</p>
<p>
<label for="A_Surname_1">Surname: <span class="req">*</span></label>
<input name="A_Surname_1" id="A_Surname_1" type="text" class="f_input" />
</p>
<p>
<label for="A_Info_1">Additional Info: </label>
<textarea name="A_Info_1" id="A_Info_1" cols="20" rows="10"></textarea>
<span class="info">Please include any infomation relating to dietary/ access/special requirements you might have.</span>
</p>
</fieldset>
</div>
<a href="#" class="add">Add more</a>
</div>
最佳答案
请参见fiddle。
将类attendee
添加到div id="att1"
<div id="att1" class="attendee">
和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
});