I am adding rows to a dynamically created table through javascript and I wanted to get its values on postback.
Here's the table:
<table id="summ" width="350px" border="1" >
Javascript snippet to add rows:
$('#summ > tbody:last').append('<tr><td><input type="button" id="delete" value="Delete"></td><td>' + sup + '</td><td>' + qty + '</td><td><input type="text"></td></tr>');
How do I get the values of the cells appended to the table after a button is clicked? "summ" is not recognized because if I put runat=server
on the table tag, the Javascript doesn't work.
2 Answers 2
You may define AJAX (WebMethod) method in code behind (add reference of System.Web.Services) and use $.ajax or $.post to request it. Have a look at code-snippet I've posted for your reference.
Sample.aspx (Code inline)
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
[WebMethod]
public static string SendData(string sup,string qty)
{
return "OK : " + sup + " " + qty;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sample Page</title>
<script src="../script/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var sup1 = 10;
var qty1 = 20;
$("#btn1").click(function () {
var arg = '{sup: ' + sup1 + ',qty:' + qty1 + '}';
$.ajax({
type: "POST",
url: "Sample.aspx/SendData",
data: arg,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert("Error: " + msg);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btn1" value="Save" />
</div>
</form>
</body>
</html>
If you want to use "runat" attribute then add an empty inside the and write ClientID attribute.
<table runat="server" id="summ" width="350px" border="1" >
<tbody>
<tr></tr>
</tbody>
</table>
jQuery code
$("#<%=summ.ClientID%> > tbody:last").append('<tr><td><input type="button" id="delete" value="Delete"></td><td>' + sup1 + '</td><td>' + qty1 + '</td><td><input type="text"></td></tr>');
OR
2 Comments
The server has no idea you were mucking about with the DOM. You can send the values back using HiddenFields:
var sup = "test";
var qty = 123;
$('#summ > tbody:last').append('<tr><td><input type="button" id="delete" value="Delete"></td><td>' + sup + '</td><td>' + qty + '</td><td><input type="text"></td></tr>');
$('#HiddenField_sup').val(sup);
$('#HiddenField_qty').val(qty);
At the server:
Response.Write(HiddenField_qty.Value);
Response.Write(HiddenField_sup.Value);
<table id="summ" runat="server" ... />
and this is an inline script, just be sure to "inject" the client id into your javascript:$'#<%= summ.ClientID %> > tbody:last').append(...);
.