Templated table rows
Use a JSON-like dataset to create table rows from a template
The server will receive an array of quantites and item numbers.
Easy to submit via AJAX
by tiagocarvalho
HTML
<form id="myOrder" action="">
<table id="orderTable">
<tbody>
<tr class="template">
<th></th>
<td>
<input type="number" name="ShopQty[]" min="0" max="9" value="1" />
<input type="hidden" name="HidMenId[]" />
</td>
<td></td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit Order" />
</form>
CSS
.template { display:none; }
#orderTable tbody th {
vertical-align:middle;
word-wrap:break-word;
width:155px;
padding-right:35px;
/*** add here your "cartHeaderRow" style definition ***/
}
#orderTable tbody td {
height:50px;
vertical-align:middle;
}
#orderTable tbody tr td:first-child {
width:75px;
}
#orderTable tbody tr td:first-child input {
width:27px;
}
#orderTable tbody tr td:last-child {
width:50px;
text-align:center;
/*** add here your "totalCalPrice" style definition ***/
}
JavaScript
$(document).ready(function () {
//create a JSON-like dataset...
var rows = [
{ menuId: 1, name: "Widget #1", unitPrice: "5.10" },
{ menuId: 2, name: "Widget #2", unitPrice: "3.09" },
{ menuId: 3, name: "Widget #3", unitPrice: "2.96" },
{ menuId: 4, name: "Widget #4", unitPrice: "6.47" }
];
$.each(rows, function (i, row) {
alert(row.name);
});
var $tbody = $("table#orderTable tbody");
var $template = $(".template", $tbody); //cache for speed
$.each(rows, function (i, row) {
var $row = $template.clone(); //clone a row template
$row.removeClass("template"); //remove the template marker
$("th", $row).text(row.name);
$("td:first input[type=number]", $row).data("unit-price", row.unitPrice);
$("td:first input[type=hidden]", $row).val(row.menuId);
$("td:last", $row).text(parseFloat(row.unitPrice).toFixed(2));
$row.appendTo($tbody);
});
$tbody.on("change", "input[type=number]", function () {
var rowTotal = ($(this).data("unit-price") * $(this).val()).toFixed(2);
$(this).closest("tr").find("td:last").text(rowTotal);
});
//planning ahead, this form could be submitted via AJAX...
$("#myOrder").submit(function () {
var $this = $(this);
/* AJAX form submission; commented out (don't know what URL to use)...
$.post("formHandler.ashx", $this.serialize(), submitSuccess, "html"); */
submitSuccess("Your order reference is: 12345"); //simulate successful AJAX
function submitSuccess(data) {
$("<p>").append(data).appendTo("body");
}
return false; //prevent full page postback
});
});