Get the ID from "append(<tr><td="ID">..." - javascript

I am filling a table with some data that I get from firebase database, and for that I am using append()
$("#table_body").append("<tr><td>" + nome + "</td>" +
"<td>" + marca + "</td>" +
"<td>" + modelo + "</td>" +
"<td>" + setor + "</td>" +
"<td>" + responsavel + "</td>" +
"<td><div buttons>"+
"<button>Delete</button>"+" "+
"<button>Edit</button>"+
"</div></td></tr>");
But then, I don't know how to use the "Remove" and "Edit" buttons on each row of the table, shouldn't I have the ID of each row? But then, how do I get the ID of each row if the rows are added dynamically?

You have an object ID from your data model ... add that as an attribute to the row.
Then use a traverse to closest() row to isolate instances
Following assumes a button with class added :
<tr data-id="idFromFirebaseObject">
....
<button class="delete-btn">Delete</button>
Then use event delegation to account for elements that don't yet exist at run time
$("#table_body").on('click','.delete-btn', function(e){
// "this" is element event occurred on
var $row = $(this).closest('tr'),
rowId = $row.data('id');
// do your thing with FB then in success callback remove row
....
$row.remove();
})

Related

Reloading modal table appends to existing table and doubles the table

I have a modal that displays informations about items (dates, etc) in a table. When I click on an item it opens a smaller modal where I can update the items date, which is then updated throught a webservice to the database. then I want to reload the data to show the updated ETA. The way I found to do that is to recall the open function of my modal. But then when I do that the modal reloads and the table is now doubled. So it probably appends to the existing table without clearing the data. How can I clear the content and reload it fresh with the updated data ? Preferably without closing and reopening the modal. Heres my code.
First is the function that saves the change and closes the small modal
$('#btnSaveETAChange').click(function () {
var dt_eta = document.getElementById('<%=EtaDate.ClientID%>').value;
var no_item = document.getElementById('<%=ItemNo.ClientID%>').value;
var no_document = document.getElementById('<%=NoPo.ClientID%>').value;
var no_line = document.getElementById('<%=LineNo.ClientID%>').value;
var no_project = document.getElementById('<%=ProjectNo.ClientID%>').value;
UpdateEta(no_item, dt_eta, no_document, no_line)
$('#modalUpdateETA').modal('hide');
$('#modalUpdateETA').on('hidden.bs.modal', function () {
$('body').removeClass('modal-open');
OpenModaleShortage(no_project);
});
});
This the function that loads the main modal.
function OpenModaleShortage(ProjectNumber) {
$("#Shortage_body tr").remove();
$.ajax(
{
type: "POST",
url: '<%=ResolveUrl("~/MTL/SEPTOR/wsMTL.asmx/GetProjectOutstandingItems") %>',
contentType: "application/json; charset=utf-8",
data: "{ 'ProjectNumber': '" + ProjectNumber + "'}",
dataType: "xml",
success: function (data) {
var rowMaterial = "<tr>"
+ "<th style='text-align:center; font-size:16px'>Item No</th>"
+ "<th style='text-align:left; font-size:16px'>Description</th>"
+ "<th style='text-align:center; font-size:16px'>Shortage</th>"
+ "<th style='text-align:center; font-size:16px'></th>"
+ "<th style='text-align:center; font-size:16px'>ETA</th>"
+ "</tr>";
$("#Shortage tbody").append(rowMaterial);
$(data).find('SHORTAGE').each(function (i, productionRow) {
try {
rowMaterial = "<tr>"
+ "<td id='no_po' style='display: none; '>" + $(productionRow).find('PO').text() + "</td> "
+ "<td id='no_line' style='display: none; '>" + $(productionRow).find('LineNO').text() + "</td> "
+ "<td id='no_item' style='text-align:center; font-size:14px'>" + $(productionRow).find('ItemNo').text() + "</td> "
+ "<td id='no_project' style='text-align:center; font-size:14px'>" + $(productionRow).find('ProjectNo').text()+ "</td> "
+ "<td style='text-align:left; font-size:14px'>" + $(productionRow).find('Description').text() + "</td> "
+ "<td style='text-align:center; font-size:14px'>" + parseInt($(productionRow).find("ProjectShortage").text()) + "</td> "
+ "<td style='text-align:center; font-size:14px' data-toggle='modal'><div><i style='vertical-align: center;' class='fa fa-calendar'></i></div></td> "
+ "<td id='dt_eta' style='text-align:center; font-size:14px'>" + $(productionRow).find('ETA1').text().slice(0, 10).trim().replace('-', '.').replace('-', '.') + "</td>"
+ "</tr>";
$("#Shortage tbody").append(rowMaterial);
}
catch (err) {
alert(err.message);
}
});
$('#addShortage').modal('show');
},
failure: function (errMsg) {
alert(errMsg);
}
}
);
};
Pretty easily, it turns out. You'll want to use the jQuery empty() method
Before you stick any data into id Shortage tbody, just empty that div out. Then, when you append new data in, it should take its place.
Admittedly, I'm uncertain how this will go down with a tbody, so you may wind up needing to delete the whole table and then re-draw the whole table, but that's not a certain thing.
Turns out the best practical answer I've come up with is to rework my page using knockout.js.
(http://learn.knockoutjs.com/#/?tutorial=intro).
By binding my view to observables. I will save the trouble of ever having to deal with those situations again.

Can't display the json data which I got from my woocommerce store to another website

I want to post the detail of woocommerce orders like id, address, name etc of my woocomerce website to a page of another website of mine. I am getting responses in http://www.baruipurjn.in/wp-json/wc/v2/orders. I want to post the order details. I have successfully included the jQuery file in my functions.php file. My jQuery code is here. I am completely new in json and jquery. Please help.
jQuery(function($){
$.getJSON( "http://www.baruipurjn.in/wp-json/wc/v2/orders", function(data) {
var ordersData='';
$.each(data, function(key,value){
ordersData += "<tr>";
ordersData += "<td>" + value.id + "</td>";
ordersData += "<td>" + value.number + "</td>";
ordersData += "<td>" + value.total + "</td>";
ordersData += "</tr>";
});
$("orders").append(ordersData);
});
});
The id of the table where I want to put the data is "orders"

DataTable JQuery | Reinitialize and getting the column & row

I have a data table in my page with the status column and view details column. after clicking view details it will pop up a modal, the modal contains a dropdown for status that when changed a certain value in the database will change. However after closing the modal the value in the datatable doesn't change. How can I reload the data table without reinitializing it, or how to get the column & row that i clicked so that I can change the value of the certain column & row. I have this code for initializing the datatable on doc.ready
function createTable(data){
for (i in data){
var message = "<tr>";
var statusHolder = "";
if(data[i].status == "open"){
statusHolder = "Open";
} else if (data[i].status == "resolved"){
statusHolder = "Resolved";
} else {
statusHolder = "Closed";
}
var id = data[i].id;
message+= "<td>" + statusHolder + "</td>";
message+= "<td><input id = 'ticketId' type ='hidden' value = " + data[i].id +" /><input type = 'hidden' id = 'support-type-name' value = 'call-back'/><a href='javascript:retrieveCommentsInfo(" + data[i].id +")' id='view-ticket-info'>" + " View details" + "</span></td>";
message+= "<td>" + data[i].id + "</td>";
$("#callback-request-body").append(message);
}
$("#callback-request-table").dataTable({
"columnDefs": [ {"visible": false, "targets": [6]},
]
});
}
Answered! So I used this created a function the will reintialize datatables.
function reInitializeDataTables(){
callbackTable.destroy();
$("#callback-request-body").empty();
retrieveCallBackRequests();
contactUsTable.destroy();
$("#contactus-table-body").empty();
retrieveContactUsMessages();
}
I'll just use .destroy() function to the datatable and then remove all contents of the body of the data table.

Event doesn't work when element isn't loaded directly

I have a table with many checkboxes which is generated with Ajax :
$.ajax({
type: "GET",
url: "jsonDevisUtilisateur.php?ra=" + $('#ra').val(),
success: function(data) {
var table = "<table class='dvs'><tr><td>Numéro</td><td>Client</td><td>Site</td><td>Libellé</td><td>Statut</td><td></td></tr>"
for (var i = 0; i < data.length; i++) {
table += "<tr><td>" + data[i].numDevis + "</td>";
table += "<td>" + data[i].client + "</td>";
table += "<td>" + data[i].site + "</td>";
table += "<td>" + data[i].libelle + "</td>";
table += "<td>" + data[i].statut + "</td>";
table += "<td><input type='checkbox' class='box' value='" + data[i].id + "' name='box[]'></td></tr>"
}
table += "</table>";
document.getElementById('devis').innerHTML = table + "<br/><br/>";
}
});
This part is working well !
The problem is when I'm trying to integrate a "select all" button.
My Javascript for it :
$(document).ready(function() {
$("#selectall").on("change", function(e) {
$("input[type=checkbox]").prop("checked", $(this).prop("checked"));
});
});
When my select all checkbox : <input type='checkbox' id='selectall' name='selectall'> is created on the same time than my HTML, it works.
But if I create my <input type='checkbox' id='selectall' name='selectall'> in my TABLE with my ajax function, it doesn't work, and nothing happens.
I'm pretty sure it is because the event is set to "selectall" at the load of the page but it doesn't exist yet and it doesn't look for it later.
What would be the solution ? Thanks for help
You can use event delegation as follow:
$('#devis').on("change", "#selectall", function(e) {
$("input[type=checkbox]").prop("checked", $(this).prop("checked"));
});
You are right in your thinking :
If your selectall checkbox is created after the document ready code execution, jquery can't find it (as it's not created yet).
I won't recommand using the live function as it is deprecated and can be removed in futur version of jquery.
You can still use the on function but with a little modification :
$("#devis").on("change", "#selectall",function(e) {
Note that #mycontainer MUST exist on document load.
If you can't place a container, this will always work :
$("body").on("change", "#selectall",function(e) {

Javascript passing parameters from form to function --> update DB

can anyone help please. I have a form generated dynamically, when it is submitted it should send values to a function and add them back to a database. I'm having real problems getting this to work, it seems simple: 1. Form --> 2. submit received --> 3. update function. The code is below:
Dynamically generated form:
function renderResults(tx, rs) {
e = $('#status');
e.html("");
for(var i=0; i < rs.rows.length; i++) {
r = rs.rows.item(i);
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input value=\"" + r.name + "\" name=\"name\" />" +
"<input value=\"" + r.amount + "\" name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});
}
}
Handles the form submit and passes to function:
$('#theform').submit(function() {
updateRecord($('#thename').val(), $('#theamount').val());
});
Function to set values:
function updateRecord(id, name, amount) {
db.transaction(function(tx) {
tx.executeSql('UPDATE groupOne SET (name, amount) VALUES (?, ?) WHERE id=?', [name, amount, id], renderRecords);
});
}
The DB update code has the id set to 4 as a test just to see if anything happens to row 4, i've been fiddling with this line for ages to get it to work. If i set it to:
tx.executeSql('UPDATE groupOne SET name = 4, amount = 5 WHERE id=?', [id], renderRecords);
it will work with set values, but can someone help me get the form values into it please.
You are missing the row id in your jQuery selector. You are passing:
$('#thename').val();
But your field has an id of "thename" + r["id"]:
'<input type="text" ... id="thename' + r['id'] + '" ...>'
You need to get your value by passing the full input id.
$("#thename" + rowId).val();
Edit: Looking more closely at your code, I notice you are creating multiple forms with the same id, which is invalid html. I see now that you've got one form per record. Good, just lose the id from the form and its inputs. Instead, use names for the inputs.
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input name=\"name\" />" +
"<input name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});

Categories

Resources