in my project i have this JavaScript function as shown below;
function refTable(clickon) {
t_threads = document.getElementById("tab_threads");
//Activate timeline for specific thread on active thread onclick in table
t_line = document.getElementById("tline");
t_lineH1 = GetElementInsideContainer("tl_tit", "tl_h4");
var c_type = clickon;
$.ajax({
type: "POST",
url: "trefresh",
data: {},
success: function (data) {
t_threads.innerHTML = "";
$.each(data, function (index) {
var row = t_threads.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = data[index].OptionID;
cell2.innerHTML = data[index].OptionKey;
cell3.innerHTML = data[index].OptionVal;
cell4.innerHTML = data[index].OptionVal2;
cell5.innerHTML = data[index].OptionThread;
});
var rows = t_threads.rows; // or table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].onclick = (function() { // closure
var cnt = i; // save the counter to use in the function
return function() {
task_det(this.cells[0].innerHTML);
t_line.style.visibility='visible';
t_lineH1.innerHTML = "TIMELINE FOR PROC. ID: "+this.cells[0].innerHTML;
c_type = this.cells[4].innerHTML;
getTline(c_type)
//alert("row"+cnt+" data="+this.cells[0].innerHTML);
}
})(i);
}
}
});
alert(c_type);
setTimeout(refTable.bind(c_type), 10000);
}
the problem is that anytime the global var c_type is populated in my jquery function, at the and, where i place alert, the variable result 'undefined'
How can i make c_type global and save it's value?
Thanks in advance
To make a variable global just declare it outside of a function
var c_type = clickon;
and other option could be defining it in the global object, which in browser would be the window..
window.c_type = clickon;
Anyway isn't a good Practice defining global variables, it might cause so trouble with other third part libraries.
Note:
make sure you don't define the same variable, inside a function you want to work with, in that case the function will take the variable defined in the function...
Related
I have a program that pulls from an API and displays the results on a table. What should be happening is that each row should be different data. However, when this runs, it adds the data with the ID of 4 twice, completely skipping over the data with the ID of 3. At first, I thought I must've goofed something up with the GET requests. I went to check, and turns out it is getting the data, but not adding it to the table. I moved all of the code to add to the table inside of the for loop, but the same problem happened. If it's any use, I'm using Tomcat to handle the API.
Attached is the function I use to add rows to the table.
function addRow(tableName, rowData) {
for (var h = 0; h < rowData.length; h++) {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
if(ajaxRequest.status == 200){
let table = document.getElementById(tableName);
let row = table.insertRow(1);
var order = JSON.parse(ajaxRequest.responseText);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
var cell8 = row.insertCell(8);
var cell9 = row.insertCell(9);
var cell10 = row.insertCell(10);
cell0.innerHTML = order.id;
cell1.innerHTML = order.name;
cell2.innerHTML = order.time;
cell3.innerHTML = order.type;
cell4.innerHTML = order.creamerAmount + " " + order.creamerType;
cell5.innerHTML = order.sugarAmount;
cell6.innerHTML = order.coffeeType;
cell7.innerHTML = order.teaType;
cell8.innerHTML = order.hotChocolateType;
cell9.innerHTML = order.smoothieType;
cell10.innerHTML = order.protein;
} else {
//I'm aware this is bad, not sure how to handle it otherwise though...
h--;
}
}
}
ajaxRequest.open('GET', 'http://localhost:13760/cafe/cafe/orders/' + rowData[h]);
ajaxRequest.send();
}
} ```
Looks like Andreas is right.
Try const ajaxRequest = ... instead of var ajaxRequest = ....
It's hard for me to explain in detail what is happening here. My guess is the following:
As said above, you use the same ajaxRequest, as if it would be declared before the for loop.
Secondly, as the request is async, it gets sent from the event loop after the main thread code is completed. Which means it sends the request to id = 4 two times.
Still I can be mistaken in the details (and please correct me if I'm wrong), but changing var to const should help. Have you tried it?
I got this function for a CRUD to receive some data and charge it to the html:
async function loaded() {
let data = await getRequest('http://localhost/ALMACEN/Backend/get.php');
document.getElementById("imagen").innerHTML =
'<img src="Front-End/imagenes/' + data.data[0].prod_img + '" width="50%"; height= "auto";>';
for (var i = 0; i < data.data.length; i++) {
var table = document.getElementById("employeeList").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.data[i].prod_nombre;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.data[i].prod_precio;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.data[i].prod_cantidad;
cell4 = newRow.insertCell(3);
cell4.innerHTML = `🡁
🠿
Borrar`;
}
}
I wanna get back the values to make the Delete button work, what can I do?
Add the key fields to data attributes on the button for easy access:
Borrar`;
Then in JS:
$(".delete-button").on("click", function() {
var id = $(this).data("id");
});
If you're generating the elements dynamically, you might need to bind the click event to the document instead of the button.
You can use any and multiple data attributes: data-uid, data-name, etc.
using jquery you can use this
$('#employeeList').on('click', '.opis', function(e){
e.preventDefault();
var fila=$(this).closest('tr');
var name= fila.find("td:eq(0)").text();
alert("name: "+name);
$("#name").html(name);
})
I feel like this is probably an issue with the loop somewhere, but I am a bit newer to coding and I am having trouble figuring out where exactly the issue is.
Every time I add a new task to the list, it prints the first task again. So if i add a second task, it inserts the first task and second task into the table, if i add a third task it inserts the first task and third task into the table.. its weird.
I looked in my local storage files, and its being stored properly. as in, (task one, task two, task three) no repetition there and its getting stored the way I want it to.
The issue is I am trying to do this:
I want to loop through the array, and have everything that is stored in local storage be posted on the table. (Currently, when I refresh it resets completely. its acting like session storage rather than local storage. it shows up in local storage after I refresh, but as soon as I click to add more after the refresh it disappears)
its a to do list, so I want it to basically show all items by looping through the array, and when I add a new item, have it store that and loop through the array again and post it on the table.
var table = document.getElementById("tableBody");
toDoArray = [];
function buildTable(){
addToStorage();
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
var addTheTaskName = parsedObject.taskName;
var addTheTaskDate = parsedObject.taskDate;
for(i=0; i < toDoArray.length; i++){
var row = table.insertRow(0);
var cellName = row.insertCell(0);
var cellDate = row.insertCell(1);
var cellId = row.insertCell(2);
var cellCheck = row.insertCell(3);
cellName.innerHTML= parsedObject[i].name;
cellDate.innerHTML= parsedObject[i].date;
var checkStuff = "<input type='checkbox'>";
cellCheck.innerHTML = checkStuff;
}
}
function submitForm(name,date) {
var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = getTaskObj(addTaskName,addTaskDate);
toDoArray.push(taskSomething);
buildTable();
};
function getTaskObj(taskName,taskData){
var taskObject = {
name: taskName,
date: taskData,
};
return taskObject;
}
function addToStorage(){
var storedArray = JSON.stringify(toDoArray);
localStorage.setItem("task",storedArray);}
When you are calling buildTable in submit form, its looping over the whole array again and adding the elements to table. Try this,
var table = document.getElementById("tableBody");
toDoArray = [];
function buildTable(){
addToStorage();
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
var addTheTaskName = parsedObject.taskName;
var addTheTaskDate = parsedObject.taskDate;
for(i=0; i < toDoArray.length; i++){
addTaskToTable(parsedObject[i]);
}
}
function addTaskToTable(obj){
var row = table.insertRow(0);
var cellName = row.insertCell(0);
var cellDate = row.insertCell(1);
var cellId = row.insertCell(2);
var cellCheck = row.insertCell(3);
cellName.innerHTML= obj.name;
cellDate.innerHTML= obj.date;
var checkStuff = "<input type='checkbox'>";
cellCheck.innerHTML = checkStuff;
}
function submitForm(name,date) {
var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = getTaskObj(addTaskName,addTaskDate);
toDoArray.push(taskSomething);
addTaskToTable(taskSomething);
};
function getTaskObj(taskName,taskData){
var taskObject = {
name: taskName,
date: taskData,
};
return taskObject;
}
function addToStorage(){
var storedArray = JSON.stringify(toDoArray);
localStorage.setItem("task",storedArray);
}
Here's the snippet with my comments.
var tasksStorageName = 'myTasks';
var tasksTable = document.getElementById("tasks_table");
var saveBtn = document.getElementById("save_task_btn");
var tasksList;
var storage = getStorage();
// this is dirty workaround, because localStorage disabled
// due to security reasons. feel free to remove this function
// and use localStorage directly
function getStorage() {
try {
return window.localStorage;
}
catch(e) {
return {
get: function(key) {
return JSON.stringify([
{
id: Date.now(),
name: 'first task',
date: '10/10/2016',
done: false
}
]);
},
set: function(key, object) {
}
};
}
}
function getTasksList() {
var dumpedTasks = storage.get(tasksStorageName);
// in case there are no tasks saved we return empty list
// otherwise parse our tasks.
return dumpedTasks == null ? [] : JSON.parse(dumpedTasks);
}
function dumpTaskList(tasksList) {
var dumpedTasks = JSON.stringify(tasksList);
storage.set(tasksStorageName, dumpedTasks);
}
// try to reuse things, so we have `renderTasks` function
// to render all our tasks to table which uses `renderTask`
// for each task. later we'll use it to add our newly created
// tasks.
function renderTasks(tasks) {
for (var index = 0; index < tasks.length; index++) {
var task = tasks[index];
renderTask(task);
}
}
// helper function to create checkbox
function createCheckboxForTask(task){
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = task.done;
return checkbox;
}
function renderTask(task) {
var taskRow = tasksTable.insertRow();
var doneCell = taskRow.insertCell();
var nameCell = taskRow.insertCell();
var dateCell = taskRow.insertCell();
taskRow.id = task.id;
doneCell.appendChild(createCheckboxForTask(task));
nameCell.innerText = task.name;
dateCell.innerText = task.date;
}
function createTask(name, date) {
return {
// quite naive id generation, don't use it in production
id: Date.now(),
name: name,
date: date,
done: false
}
}
// to restore your previously added tasks
// you need to get them from localStorage
// on load event and render them.
window.addEventListener('load', function(e) {
tasksList = getTasksList();
if (tasksList.length > 0) {
renderTasks(tasksList);
}
});
saveBtn.addEventListener('click', function() {
var name = document.getElementById("task_name").value;
var date = document.getElementById("task_date").value;
var newTask = createTask(name, date);
tasksList.push(newTask);
renderTask(newTask);
dumpTaskList(tasksList);
});
/*
// function does too many things
function buildTable(){
// if you try to call `buildTable` at page load then
// `addToStorage` function will set localStorage task item
// to empty array. thats why you lost your state every time
// you reload page
addToStorage();
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
// why this two unnecessary variables?
var addTheTaskName = parsedObject.taskName;
var addTheTaskDate = parsedObject.taskDate;
for(i=0; i < toDoArray.length; i++){
addTaskToTable(parsedObject[i]);
}
}
// try to give parametes as well as variables meaningful names
// like `task` this time, not `obj`
function addTaskToTable(obj){
var row = table.insertRow(0);
var cellName = row.insertCell(0);
var cellDate = row.insertCell(1);
var cellId = row.insertCell(2);
var cellCheck = row.insertCell(3);
cellName.innerHTML= obj.name;
cellDate.innerHTML= obj.date;
var checkStuff = "<input type='checkbox'>";
cellCheck.innerHTML = checkStuff;
}
function submitForm(name,date) {
var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = getTaskObj(addTaskName,addTaskDate);
toDoArray.push(taskSomething);
addTaskToTable(taskSomething);
};
// actually you are creating new task object, not getting it
// from somewhere, so it's better to name it like createTask
// or newTask
function getTaskObj(taskName,taskData){
var taskObject = {
name: taskName,
date: taskData,
};
return taskObject;
}
function addToStorage(){
var storedArray = JSON.stringify(toDoArray);
localStorage.setItem("task",storedArray);
}
*/
<div>
<label>Name: </label>
<input id="task_name" type="text"/>
</div>
<div>
<label>Date: </label>
<input id="task_date" type="text"/>
</div>
<button id="save_task_btn" type="button">Save</button>
<table id="tasks_table">
<thead>
<tr>
<th>Done</th>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
<table>
i'm getting some html input values with javascript that i insert in a table , but those turned null when i refresh , how can i keep those value visible after refresh . I know i should set and get my cookies but i just don't how .
here is my javascript code :
function myFunction(tableID) {
var x = document.getElementById("name").value;
var ad = document.getElementById("address").value;
var nu = document.getElementById("tel").value;
var pr = document.getElementById("product").value;
var s = document.getElementById("size").value;
var d = document.getElementById("date").value;
var st = document.getElementById("statu").value;
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = x;
var cell2 = row.insertCell(1);
cell2.innerHTML = ad;
var cell3 = row.insertCell(2);
cell3.innerHTML = nu;
var cell4 = row.insertCell(3);
cell4.innerHTML = pr;
var cell5 = row.insertCell(4);
cell5.innerHTML = s;
var cell6 = row.insertCell(5);
cell6.innerHTML = d;
var cell7 = row.insertCell(6);
cell7.innerHTML = st;
}
any help ?
THanks
One way to do it would be to stick them in sessionStorage (which will be accessible across page refreshes).
To store them:
sessionStorage.setItem('foo', 'bar');
to get them:
sessionStorage.getItem('foo');
When your page is loaded, you can get them from the sessionStorage to repopulate your elements.
you can use localStorage
// before you leave your page , save all your variables here
window.onunload = function(){
// save them one by one in to localStorage
localStorage.setItem("x", x)
...
}
when you enter the page load from localStorage first :
// before all your code work.
window.onload = function (){
// set value back one by one
document.getElementById("name").value = localStorage.getItem("x");
...
}
I am trying to move an object from one localStorage to another localStorage based on whether or not a checkbox in a table is ticked.
// version 1.0
// Developer
// Date: Tuesday December 29th 2015
// Registeration for Cars and stuff as well as table to retreive the Car information
var Car = [];
function carReg(storagekey) {
alert('submitted');
"use strict";
// checks localstorage to see if there are already values and then keeps those values rather than deleteing them
//Car = JSON.parse(localStorage.getitem(storagekey));
// if (Car == null) {
// Car = [];
// }
// push all of the data into localStorage under the specific variable id's
Car.push({
Brand: document.getElementById("mySelect").value,
Model: document.getElementById("selectModel").value,
Age: document.getElementById("carAge").value,
KM: document.getElementById("km").value,
Name: document.getElementById("name").value,
ContactInfo: document.getElementById("cInfo").value,
})
// stores everthing into local storage under the specified key
localStorage.setItem(storagekey, JSON.stringify(Car))
}
/////////////////////////////
/// Table Code starts here//
///////////////////////////
function maketable() {
// get data from localStorage
var carReg = JSON.parse(localStorage.getItem("register"))
// Variables for the table values and classifications
var table, row, cell1, cell2, cell3, cell4, cell5, cell6;
table = document.getElementById('ownedCar')
// Row definers
for (var index = 0; index < carReg.length; index++) {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = index;
row = table.insertRow(index+1)
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell5 = row.insertCell(4);
cell6 = row.insertCell(5);
cell7 = row.insertCell(6);
// row classifications
cell1.innerHTML = carReg[index].Brand
cell2.innerHTML = carReg[index].Model
cell3.innerHTML = carReg[index].Age
cell4.innerHTML = carReg[index].KM
cell5.innerHTML = carReg[index].Name
cell6.innerHTML = carReg[index].ContactInfo
cell7.appendChild(checkbox);
}
}
function selling() {
//query from localStorage
var carReg = JSON.parse(localStorage.getItem("register"))
for (var index = 0; index < carReg; index++) {
if (!(document.getElementById(index).checked)) {
index = localStorage.setItem("sell", JSON.stringify(carReg))
}
}
}
Basically the part that should be doing this is this.
function selling() {
//query from localStorage
var carReg = JSON.parse(localStorage.getItem("register"))
for (var index = 0; index < carReg; index++) {
if (!(document.getElementById(index).checked)) {
index = localStorage.setItem("sell", JSON.stringify(carReg))
}
}
}
But it isn't doing anything. Is there something that I'm missing? Or is it just that my if statement part is wrong?
I found what the answer was I was missing a '.length' in my for statement. Thanks wapsee!