This is my table, and I want to add a column to the right where a user will be able to enter a value and save. (It needs to save the value to a sql table)
Code in my View:
<tbody>
@foreach (var items in Model.tbl_Stuff)
{
<tr>
<td>@items.ID</td>
<td>@items.Description</td>
<td><input type="text" id="txtAmount" /></td>
</tr>
}
</tbody>
This is the Javascript: In the function is where I should be able to update each row, how do I loop though a table row, and update the inserted value on the new column to the sql table via the controller action? EDIT: this is my edited script according to the suggestion below, it sends the value to controller.
<script type="text/javascript">
$("body").on("click", "#btnSave", function () {
var stuffarray= new Array();
var txtEmployeeBidAmount = $("#txtEmployeeBidAmount");
$("#tblStuff TBODY TR").each(function () {
var row = $(this);
var stuf= {};
stuf.Amount = row.find("TD").eq(4).html();
stuffarray.push(stuf);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "@Url.Action("UpdateStuff","Home")",
data: JSON.stringify(stuffarray),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r " record(s) saved.");
}
});
});
CodePudding user response:
As you have a table, you require to loop the table using the following sample to get text box value from each row:
HTML:
<table>
<tbody>
<tr>
<td>63</td>
<td>Computer</td>
<td>3434</td>
<td><input type='text' class='val' value='100' /></td>
</tr>
<tr>
<td>64</td>
<td>Stationary</td>
<td>111</td>
<td><input type='text' class='val' value='200' /></td>
</tr>
<tr>
<td>64</td>
<td>Stationary</td>
<td>11</td>
<td><input type='text' class='val' value='400' /></td>
</tr>
</tbody>
</table>
jQuery:
var table = $("table tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
Id = $tds.eq(0).text(),
Product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
Val = $tds.find('.val').val();
alert('Row ' (i 1) ':\nId: ' Id
'\nProduct: ' Product
'\nQuantity: ' Quantity
'\nVal: ' Val);
});
Finally add them to an JavaScript
array object to update in the controller.
Here's a sample in JSFiddle