I would like to clone a select and update the name
and id
values. The select is within a <tr><td>
<table>
<tr id="tr_1">
<td id="td_1">
<select name="tech_1" id="tech_1">
<option value="0">Please Select</option>
<option value="1">Mango</option>
<option value="2">Apple</option>
<option value="3">Banana</option>
<option value="4">Orange</option>
</select>
</td>
</tr>
</table>
<input type="button" id="btnClone" value="Clone" />
I can do it without the table, but my challenge is putting the clone within a new <tr><td>
... </td></tr>
Here is my jquery:
$("#btnClone").bind("click", function () {
// get the last SELECT which ID starts with ^= "tech_"
var $tr = $('tr[id^="tr_"]:last');
// get the last SELECT which ID starts with ^= "tech_"
var $select = $('select[id^="tech_"]:last');
// Read the Number from that SELECT's ID (i.e: 3 from "tech_3")
// And increment that number by 1
var num = parseInt( $select.prop("id").match(/d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "tech_4")
var $klon = $select.clone().prop('id', 'tech_'+num ).prop('name', 'tech_'+num );
// Finally insert $klon wherever you want
$tr.after("<tr><td>").after($klon).after("</td></tr>");
});
This code results in the cloned <select>
below the original and nothing between the new <tr><td>
and </td></tr>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…