Update entire HTML table column using JS - javascript

I want to update entire column with new_data
I tried to update as bellows
response.json().then(function (new_data){
console.log(new_data)
var body_data = " ";
new_data.forEach((item) => {
var list_data = "";
list_data += "<td>" + item.vc_state + "</td>";
body_data += list_data;
});
$('#vc_state').html(body_data); })
But it update only the cell as bellows
I want to update entire State column with new data
Please help me to solve this
Updated
I updated as follows
response.json().then(function (data){
console.log(data)
var body_data = " ";
data.forEach((item) => {
var list_data = "";
list_data += "<td>" + item.vc_state + "</td>";
$('#vc_state').replaceWith(list_data);
});
It worked. But it changed the HTML only once . I need to update HTML when I call the function without refreshing the page

watch table infor with w3c will help you. table>thead|tbody>tr>td|th.

Related

Cant access object that have been declare on javascript

I'm trying to get some value over my server using jquery's $.get method and store the result in an object.
What I'm doing is running my function inside a loop:
function renderTabelScheduledEmploye(employees) {
$('#containerDataStaff').empty();
let record = '';
let count = 1;
if (employees.length > 0) {
$.each(employees, function(key, value) {
getFromServerScheduleCount(employees[key].schedule_employee_id);
console.log(scheduleCountData);
record += '<tr>';
record += '<td>' + count + '</td>';
record += '<td>( ' + employees[key].emp_kode + ') - ' + employees[key].emp_full_name + '</td>';
record += '<td>' + scheduleCountData[0].work + '</td>';
record += '<td>' + scheduleCountData[0].offDay + '</td>';
record += '<td>' + scheduleCountData[0].leave + '</td>';
record += '<td>' + scheduleCountData[0].shiftCount + '</td>';
record += '<td>Set Shift</td>';
record += '</tr>';
count++;
});
}
$('#containerDataStaff').append(record);
}
Then I create a function to retrieve JSON data from my server using the $.get function, then store the data result to an object that has been declared:
var scheduleCountData = new Object();
function getFromServerScheduleCount(schedule_employee_id) {
let url = `{{ url('/departement/schedule/manage/schedule/count') }}`;
url = url + '/' + schedule_employee_id + '/get';
let data = {};
$.get(url, function(data) {
let obj = JSON.parse(data);
data.work = obj.work;
data.dayOff = obj.dayOff;
data.leave = obj.leave;
data.shifts = obj.shifts;
scheduleCountData.new = data;
})
}
I can see in the console that the object has filled with the data
[object success to fill][1]
But when i try to access in code like this
scheduleCountData[0]
and log the result to to the console, it shows undefined.
This little bit frustrating for me. I hope someone can help me. Thanks for community.
EDIT :
Sorry i miss
i try to call that object with code like this
scheduleCountData.new
but still undefined on console
Seems youre not waiting for the load to finish before trying to use the data:
// This has a get call, which is async (takes time to load)
getFromServerScheduleCount(employees[key].schedule_employee_id);
// The script will continue, without waiting for the load to finish, so can be empty
console.log(scheduleCountData);
I would suggest adding a callback, like this:
getFromServerScheduleCount(employees[key].schedule_employee_id, function(scheduleCountData) {
console.log(scheduleCountData);
});
function getFromServerScheduleCount(schedule_employee_id, callback) {
$.get(url, function(data) {
// ...
callback(data);
});
}

Store Values of Checkboxes in Array in Google Apps Script

I have a dynamic array as such:
var PartnerEmailList = [one#email.com, two#email.com, three#email.com];
The following function creates a table that is displayed in a showModalDialog window.
function makeTableHTML() {
var PartnerEmailList = [one#email.com, two#email.com, three#email.com];
var result = "<table border=0>";
result += "<tr><td style=\"text-align:center\"><input type=\"checkbox\" name =" + PartnerEmailList[0] + " value =" + PartnerEmailList[0] + " checked></input></td>";
result += "<td style=\"vertical-align:text-middle\">" + PartnerEmailList[0] + "</td></tr>";
for(var i=1; i<PartnerEmailList.length; i++) {
result += "<tr><td style=\"text-align:center\"><input type=\"checkbox\" unchecked></input></td>";
result += "<td style=\"vertical-align:text-middle\">" + PartnerEmailList[i] + "</td></tr>";
}
result += "</table>";
result += "<input type=\"submit\" value=\"Submit\" class=\"action\" onclick=\"form_data()\">"
result += "<input type=\"button\" value=\"Close\" onclick=\"google.script.host.close()\">"
return result;
}
The user clicks a button within Google Sheets that runs the following script. This script pops up a ModalDialog window where the user can check which emails they want to send this product to.
function SelectEmails(){
var ui = SpreadsheetApp.getUi();
var result = makeTableHTML();
var bccSend = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('main_gen').getRange(2,2).getValue();
if(bccSend === ''){
//Call the HTML file and set the width and height
var html = HtmlService.createHtmlOutput(result)
.setWidth(450)
.setHeight(300);
//Display the dialog
var dialog = ui.showModalDialog(html, "Select the intended recipients of this briefing.");
}
}
I need to write a function that looks through all the checkboxes (they are all assigned a value within the html code) and stores the values of each one that is checked in an array. I will be calling this array in a different function to actually send out the email.
There may be a much better way to go about this, but this is what I have come up with so far. Any help would be much appreciated! Thanks!

Javascript or Jquery to get div by key of div and change value of it

I have a list of tables.
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i].current_order == null) {
tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
} else {
tables += '<button class="table_selected" key="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
}
And tables have two color, when it is busy or not busy. If there is current_order in table, it shows busy. What I want to do is that when a user clicks empty table, it gets table_id, changes class from table_btn to table_selected and add keyof div, which is current_order.
I use phoenix-framework for my backend, so when a user clicks an empty table, it creates order and passes value of clicked table_id and created order_id. But I am not sure that how can I get a table by value of table div and put key into div...
Can anyone give me advice for this??
So as you tagged Jquery, i'm gonna post this. Change key for ID and you can do the following. I would then wrap the add table and remove table in functions where u pass in the data[i].current_order into and use that.
Edited based on user feeback, not tested
/*If you are not comfortable using the variable 'This',
you can just pass in the id of target table and
change the syntax to $("#"+targetTable)*/
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i].current_order == null) {
tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
} else {
tables += '<button class="table_selected" id="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
}
// On Click set table to busy
$(".table_btn").click(function(){
addTable($(this).val(), $(this));
});
// Add table function
function addTable(tableId, targetTable){
$.ajax({
url: "YourBackEndHere",
data: tableID
cache: false,
success: function(html){
$(targetTable).removeClass("table_btn");
$(targetTable).addClass("table_selected");
$(targetTable).attr("id", data[i].current_order);
}
});
}
// On click set table to empty
$(".table_selected").click(function(){
removeTable($(this).val(), $(this));
});
// Remove table function
function removeTable(tableId, targetTable){
$.ajax({
data: tableId
url: "YourBackEndHere",
cache: false,
success: function(html){
$(targetTable).removeClass("table_selected");
$(targetTable).addClass("table_btn");
$(targetTable).attr("id", "");
});
}
});
}

JSON save selected items on array and pass to other page

So I have 2 pages.
On one I have a table that is getting data from a JSON page and I inserted a button on each row that whenever is clicked it should get that item on an array.
And then, that array should give the results on the second page.
I can get the info from the JSON without problems, but cannot store the information on an array. Can someone help me? I'm quite new on JavaScript.
Page 1:
<script>
<!-- Retrieve data from file -->
var products=[];
var cartArray=[];
var product_array=[];
$.getJSON('products.json',function(data){
$.each(data.products, function(i, f){
var img = f.image_url;
var title = f.title;
var price = f.price;
var old_price = f.old_price;
product_array.push([img, title, price]);
var tblCell = "<tr><td class='prod_container'><tr><td class='prod_img_container'><img class='prod_img' src=" + img + "></td></tr>" + "<tr class='title_container'><td class='title'>" + title + "</td></tr>" + "<tr class='price_container'><td class='price'>" + price + "</td>" + "<td class='price_org'>" + old_price + "</td>" + "<td class='add_cart'><img class='add_cart_img' src='img/buynow-green-6.png' onClick='addToCart()'>" + "</td></tr>"
$(tblCell).appendTo("#list_products tbody");
});
});
<!-- Add To Cart -->
function addToCart(){
cartArray.push([product_array.title, product_array.img, product_array.price]);
window.alert(cartArray);
}
<!-- Store and go to checkout -->
function goToCheckout(){
$('#store').on('click', function(){
localStorage.cartArray = cartArray;
});
window.location.href="cart.html";
}
Not sure of your final data structure needs, but if you want a multi-dimensional array:
var cartArray = []
function addToCart(product_array){
cartArray.push([product_array.title, product_array.img, product_array.price];
window.alert(cartArray);
}

Adding a row to JSON

I want to add a new row to my JSON when the user clicks a link. Here's my javascript: It's not erroring, but I am not getting updated JSON in my alert.
$(document).ready( function(){
people = {
"COLUMNS":["NAME","AGE"],
"DATA":[
["Jon","16"],
["Jerry","23"]
]
}
members = people.DATA;
var nc = "<table border=1 width=500><tr><td>name</td><td>age</td><td></td></tr>";
for(var i=0;i<members.length;i++)
{
nc+= '<tr><td>' + members[i][0] + '</td>';
nc+= '<td>' + members[i][1] + '</td>';
nc+= '<td>add a new person</td></tr>';
}
nc += "</table>";
$("#result").html(nc);
$(".addlink").click( function(){
// add another row to our JSON
people.DATA['NAME'] = "new";
people.DATA['AGE'] = "99";
alert(people.DATA);
return false;
});
});
That's not JSON, it's a Javascript object.
To add another item in the array, you create an array and add to it, as it is an array of arrays:
people.DATA.push(["new", "99"]);

Categories