ในกรณี ที่ต้องการสร้างฟอร์ม สำหรับการบันทึกข้อมูล โดยให้สามารถทำการเพิ่มรายข้อมูล ได้หลายๆ รายการในครั้งเดียว
สามารถประยุกต์ใช้ method .clone() ของ jQuery ในการเพิ่มแถวของรายการ สำหรับเพิ่มข้อมูล ได้
HTML โค้ดฟอร์มตัวอย่าง
<form id="form1" name="form1" method="post" action="">
<table id="myTbl" width="650" border="1" cellspacing="2" cellpadding="0">
<tr id="firstTr">
<td width="119"><select name="data1[]" id="data1[]">
<option value="1">data1</option>
<option value="2">data2</option>
</select></td>
<td width="519"><input type="text" name="data2[]" id="data2[]" /></td>
</tr>
</table>
<br />
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<button id="addRow" type="button">+</button>
<button id="removeRow" type="button">-</button>
<button id="Submit" type="submit">Submit</button>
</td>
</tr>
</table>
</form>
จากโค้ดด้านบน สิ่งที่ต้องกำหนด มีอยู่ 2 ที่ คือ id ของ table และ id ของ tr เพื่อใช้ในการอ้างอิงการทำงาน
<table id="myTbl" width="650" border="1" cellspacing="2" cellpadding="0"> <tr id="firstTr"> // table id="myTbl" // tr id="firstTr" .............
Javascript Code
<script language="javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#addRow").click(function(){
$("#myTbl").append($("#firstTr").clone());
});
$("#removeRow").click(function(){
if($("#myTbl tr").size()>1){
$("#myTbl tr:last").remove();
}else{
alert("ต้องมีรายการข้อมูลอย่างน้อย 1 รายการ");
}
});
});
</script>
ตัวอย่าง