单击复制链接时,我将克隆当前行。创建新行时,不会保留单选按钮的旧状态。
我需要克隆当前行,它也应该保留旧行的输入元素状态。
代码
$("#MyLastOrder tr .BtnPlus").click(function () {
$($(this).parent().parent()).clone(true, true).appendTo("#MyLastOrder");
var totalRows = document.getElementById("totalrows").value;
var qtyrow = "totalqty_" + eval(parseInt(totalRows) + 1);
var weightrow = "weight_" + eval(parseInt(totalRows) + 1);
var brandrow = "br_" + eval(parseInt(totalRows) + 1);
$("#MyLastOrder tr:last").find("input:radio").each(function () {
var curName = $(this).attr('name');
console.log("curname" + $(this).attr('name') + curName.substr(0, 2));
$(this).attr('name', function (_, id) {
var currentNameAttr = $(this).attr('name');
if (curName.substr(0, 2) == "br") {
$(this).attr('name', brandrow);
}
if (curName.substr(0, 2) == "we") {
$(this).attr('name', weightrow);
}
});
});
$("#MyLastOrder tr:last").find("select").each(function () {
var curName = $(this).attr('name');
console.log("curname" + $(this).attr('name') + curName.substr(0, 2));
$(this).attr('name', function (_, id) {
var currentNameAttr = $(this).attr('name');
if (curName.substr(0, 3) == "tot") {
$(this).attr('name', qtyrow);
}
});
});
var incTotalRows = parseInt(totalRows) + 1;
document.getElementById("totalrows").value = incTotalRows;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table" id="MyLastOrder">
<thead>
<tr id="header1">
<th>Brand</th>
<th>Type</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input name="br_1" value="13" type="radio" checked="true"> xyz<br>
<input name="br_1" value="16" type="radio"> xyz<br>
<input name="br_1" value="17" type="radio"> xyz<br>
</td>
<td>
<input name="weight_1" value="1" type="radio"> 1gm<br>
<input name="weight_1" value="2" type="radio" checked=""> 2gm<br>
</td>
<td>
<select name="totalqty_1">
<option selected="">1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
</td>
</td>
<td><a href="javascript:void(0)" class="BtnPlus"><img src="images/copyitem.png" title="Copy"></a></td>
</tr>
</tbody>
</table>
<input type="hidden" name="totalrows1" id="totalrows" value="2">
<!--this hidden is to act as counter and increment input elements name when cloning. this will be dynamically updated when a row is cloned.-->
最佳答案
它不会保留前一行的状态,因为您在新行中附加了与前一行具有相同名称的单选按钮。所以前面的内容当然不会被选中。
您要做的是首先克隆行,然后在克隆行中找到单选按钮,更改名称,然后附加克隆的行。
var $clone = $($(this).parent().parent()).clone(true, true);
$clone.find(":radio").each(function () {
// previous code
});
// and later
$clone.appendTo("#MyLastOrder");
演示:http://jsfiddle.net/q1wphkpb/
关于JQuery 克隆不保留单选和选择状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27588628/