Reputation: 4966
How can I perform the following action using jquery?
I have a table with three rows and a header row. something like this: When a user enters Data in "StudentId" field, "StudentFirstName" and "StudentLastName" are populated from database using jquery-Ajax. What I want to achieve is, Once a studentId is entered in first row textbox, I want to clone the first row and append it as second row and then clear the data from first row.
Hers is my Table structure:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%@ Import Namespace="MyModel.Model" %>
<div>
<table id="MyTableHeaders">
<tr>
<th>
StudentId
</th>
<th>
StudentFirstName
</th>
<th>
StudentLastName
</th>
</tr>
</table>
</div>
<div>
<table id="MyTableData">
<tr>
<td>
<input name="StudentId"/>
</td>
<td>
<input name="StudentFirstName"/>
</td>
<td>
<input name="StudentLastName"/>
</td>
</tr>
</table>
</div>
Here is my jquery:
$('input[name="StudentId"]').focusout(function (e) {
e.preventDefault();
var link = '/Student/DisplayStudentDetails';
$.ajax({
type: 'POST',
url: link,
data: { id: $('input[name="StudentId"]').val() },
dataType: 'json',
success: function (result) {
$('input[name="StudentFirstName"]').val(result.FirstName);
$('input[name="StudentLastName"]').val(result.LastName);
$("#MyTableData tr:first").clone().appendTo("#MyTableData");
$("#MyTableData tr:first").find("input").attr("value", "").blur();
},
error: function (result) {
alert("Failed")
}
});
});
I am struggling with clearing data from first row and keeping data in the cloned row. With my code it clears all the rows.
Also, I noticed that cloned rows have the same field names, hence it will update all cloned "StudentFirstName" and "StudentLastName" fields with the studentId entered in first row. How should I approach this?
Any help would be appreciated.
Upvotes: 0
Views: 347
Reputation: 2008
success: function (result) {
var clone = $("#MyTableData tr:first").clone();
clone.find('input[name="StudentId"]').val(result.FirstName);
clone.find('input[name="StudentFirstName"]').val(result.FirstName);
clone.find('input[name="StudentLastName"]').val(result.LastName);
$("#MyTableData ").append(clone);
},
-edit-
although, when i've attempted tasks such as this in the past, i've created template rows. a row that already exists but has display:none. that way if your table has no values you can always know the template row exists.
-edit- if you want to add the new row at the begining, you can just use prepend instead of append. or the second row would be $("#MyTableData tr").first().after(clone)
Upvotes: 1