Jquery: Clone Row and Append Index to Text Area Name/ID
I have the following table:
<table width="1000" border="1" cellpadding="2" cellspacing="2" bordercolor="#CCCCCC" class="WebApps" id="addIssue">
<tbody>
<tr>
<td bordercolor="#f0f0e4" bgcolor="#f0f0e4"><h3>Open Issues
<input type="button" class="button" value="+" id="addNewIssue" name="addNewIssue"/>
<input type="text" id="txtIndex" name="txtIndex" value="<%=vIndex%>">
</h3></td>
</tr>
<tr>
<td bordercolor="#FFFFFF" bgcolor="#FFFFFF"><p><textarea id="txtOpenIssues0" name="txtOpenIssues0" cols="100" rows="2"></textarea>
</p></td>
</tr>
</tbody>
</table>
And the following JQuery script:
$("#addNewIssue").click
(
function()
{
var iX = document.getElementById("txtIndex").value;
iX ++;
document.getElementById("txtIndex").value = iX;
$('#addIssue tbody>tr:last').clone(true).insertAfter('#addIssue tbody>tr:last');
//Clear out newly added text field.
$('#addIssue tbody>tr:last #txtOpenIssues0').val('');
return false;
}
);
It works just fine; however, as you can see from my HTML, I am trying to attach an index to the name/id of the text area. So, upon adding a new row using the Jquery script, i would like to change the name and id of the newly added row to match my index. So, row one is txtOpenIssues0, and then the newly added row would contain text field txtOpenIssues1, then add another and it'd be txtOpenIssues2, etc. I have done this successfully without JQuery,开发者_如何学Go but am wanting to try more JQuery solutions. Currently have jquery 1.6.1 Any help is appreciated. Thanks!
With just a little modding of the code I was able to get it working. You can directly change the the id and name of the node after cloning it (.clone(true).attr(...)
). and then you just use the index you are already iterating.
http://jsfiddle.net/FKuWJ/1/
$('#addIssue tbody>tr:last')
.clone(true)
.insertAfter('#addIssue tbody>tr:last')
.find("textarea")
.attr("id","txtOpenIssues" + iX)
.attr("name","txtOpenIssues" + iX)
.val('');
In jQuery there is after
method to insert anything after the element. Try this
$("#addNewIssue").click
(
function()
{
$('#addIssue tbody>tr:last')
.after($('#addIssue tbody>tr:last').clone(true));
var $lastRow = $('#addIssue tbody>tr:last');
var lastRowIndex = $lastRow.index();
//Clear out newly added text field.
$lastRow.find('#txtOpenIssues').val('')
.attr("id", "txtOpenIssues"+lastRowIndex)
.attr("name", "txtOpenIssues"+lastRowIndex);
return false;
}
);
If you are using IE for testing, mind it. Cloning sometimes does not work in IE. Especially cloning of radio buttons
精彩评论