This is connected to my previous question: How to add onclick function for programmatically created button.
Now, I currently have a form with two textboxes, a button and a hidden table. When the button is clicked, the table is displayed and a row is added with the values of the textboxes on two columns and a remove button the third. I am now able to remove selected rows when the remove button is clicked. My new problem is how can I get the data of the first and second column so I can update the database?
I use JSON to update the database. Here’s the code I currently have:
$("#addToDisplay").click(function (event) {
$("#tblProducts").removeClass("hide");
var counter = 1;
event.preventDefault();
counter++;
var prod = {prodName: $("#txtProducts").val(), prodQty: $("#txtQty").val()}
$.ajax({
type: "POST",
traditional: true,
url: "/Service/JsonUpdateProduct",
dataType: "json",
data: prod,
success: function (result) {
var newRow = "<tr><td id='rowProd" + counter + "'>" + $("#txtProducts").val() + "</td><td id='rowQty" + counter + "'>" + $("#txtQty").val() + "</td><td><input type='button' value='Remove' id='btnRemove" + counter + "' class='remove' /></td></tr>";
$("#tblProducts").append(newRow);
$("#tblProducts").on("click", ".remove", function () {
$(this).closest("tr").remove();
var rowCount = $("#tblProducts tr").length;
var removeProd = {revertName: $("#rowProd" + counter).val(), revertQty: $("#rowQty" + counter).val()}
$.ajax({
type: "POST",
traditional: true,
url: "/Service/JsonRemoveProduct",
dataType: "json",
data: removeProd,
success: function (result) {
if (rowCount == 1) {
$("#tblProducts").addClass("hide");
}
}
});
$("#productQty").val("");
$("#autoCompleteText").val("");
});
}
});
});
I’ve been trying that code but all I get is a null value for the quantity which causes an error. So how do I exactly get the data of the selected ProductName and Quantity from a selected row?
I basically am trying to get something like this:
var data = { prodName: $("#selectedRowCell1")}
so I can pass it to the method in my class and update the database.
Also, is it possible to get the current Id of a different table and insert it to another table + 1. Something like this:
Select id from Details
then
Update Products set detailId = Details.id + 1
? I know this doesn’t work as I’ve already tried it. So is something like this even possible?
First, these should be separate click events, don’t define a click event within the ajax callback. This is why you use the
on()method..on()acts as aevent delegator. Theselectoris astatic elementbound to the documenton page load and not after. This means, we can bind events to this parent element, and their children will have the event delegated to them if supplied as the 2nd argument.Here, the issue is how to get
productData. By your definition, product data are the two previous columns in the row when the.removeclass element is clicked. Let’s do it.