getting the variable's value from another funtion - javascript

Is there a way to get the 'username' and 'questionid' variable's value in my send() function like how I did with inputText?
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
var username = data[0].username;
//var examid = data[1].examid;
var questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);

You do not need var before username and questionid in your renderHTML function, as they have already been defined:
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
username = data[0].username;
//var examid = data[1].examid;
questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);

Related

Printing an object within an array showing as blank

function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var objEvent = {};
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
arrEvent.push(objEvent);
while(objEvent.name.length > 0) {
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
if(objEvent.name.length > 0) {
arrEvent.push(objEvent);
}
}
displayEvent(arrEvent);
}
window.onload = init;
Trying to print an object array into the HTML paragraph id and whenever I execute the code above I get the correct output but the array elements just show as blank.
You are always pushing the same object into your array.
Change to:
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var name = '';
var age = '';
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
arrEvent.push({name: name, age: age});
while(name.length > 0) {
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
if(name.length > 0) {
arrEvent.push({name: name, age: age});
}
}
displayEvent(arrEvent);
}
window.onload = init;

GAS/ Javascript giving wrong figures when summing up numbers

My Javascript/GAS code uses the user ID to call for time entries via API for a specific date range (1 week) and sum up the hours. These time entries are saved in an array and then summed up. The first 50 additions on the log are correct but as you go through the list you realize wrong summed figures and long decimal places. What could be wrong and what can I do to solve this. Here is my code:
var TKF_URL = 'https://api.10000ft.com/api/v1/';
var TKF_AUTH = 'auth'
var TKF_PGSZ = 2500
var from = '2020-01-06'
var to = '2020-01-22'
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + TKF_AUTH
}
};
function getUsers() {
var userarray = [];
var lastpage = false;
var page = 1;
do {
// gets 10kft data
var users = read10k_users(page);
// writes data from current page to array
for (var i in users.data) {
var rec = {};
// pushing of mandatory data
rec.id = users.data[i].id;
rec.display_name = users.data[i].display_name;
rec.email = users.data[i].email;
userarray.push(rec);
}
// checks if this is the last page (indicated by paging next page link beeing null
if (users.paging.next != null) {
lastpage = false;
var page = page + 1;
} else {
lastpage = true;
}
}
while (lastpage == false);
return (userarray);
return (userarray);
}
function read10k_users(page) {
var endpoint = 'users?';
var url = TKF_URL + endpoint + 'per_page=' + TKF_PGSZ + '&auth=' + TKF_AUTH + '&page=' + page;
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response);
//Logger.log(json.data)
return (json);
}
function showTimeData() {
var users = getUsers()
var endpoint = 'users/';
var time_array = [];
for (var i = 0; i < users.length; i++) {
var total_hours = 0;
// Logger.log(users[i].id)
var url = 'https://api.10000ft.com/api/v1/users/' + users[i].id + '/time_entries?fields=approvals' + '&from=' + from + '&to=' + to + '&auth=' + TKF_AUTH;
var response = UrlFetchApp.fetch(url, options);
var info = JSON.parse(response.getContentText());
var content = info.data;
for (var j = 0; j < content.length; j++) {
total_hours += content[j].hours;
// }
//
// if(total_hours < 35){
//
// sendMail(user[i]);
//
// }
Logger.log('User name: ' + users[i].display_name + ' ' + 'User id: ' + users[i].id + ' ' + 'total hours: ' + total_hours)
}
}
function sendMail(user) {
var emailAddress = user.email;
var message = 'Dear ' + user.display_name + 'Your timesheets is incomplete , please visist 10k Ft and commlete your timesheet'
var subject = 'TimeSheet';
MailApp.sendEmail(emailAddress, subject, message);
}
}
Log results
You have total_hours declared outside of your loop. So what you are doing is calculating the total hours all workers combined, not total hours per worker.
(removed a lot of code to show only the important parts for your bug)
function showTimeData() {
var users = getUsers()
var total_hours = 0; // you declare the variable here
for (var i = 0; i < users.length; i++) {
var content = info.data;
// Calculate the sum for current user
for (var j = 0; j < content.length; j++) {
total_hours += content[j].hours;
}
// Check if total_hours for ALL workers is less than 35
if (total_hours < 35) sendMail(user[i]);
// total_hours is not reset, so the sum is used in next iteration.
}
}
Move the declaration of total_hours to inside the loop, or reset it to zero.
function showTimeData() {
for (var i = 0; i < users.length; i++) {
var total_hours = 0; // you declare the variable here
}
}
Your loop should look something like this:
for (var i = 0; i < users.length; i++) {
var total_hours = 0;
var url = "https://api.10000ft.com/api/v1/users/" + users[i].id + "/time_entries?fields=approvals" + "&from=" + from + "&to=" + to + "&auth=" + TKF_AUTH;
var response = UrlFetchApp.fetch(url, options);
var info = JSON.parse(response.getContentText());
var content = info.data;
for (var j = 0; j < content.length; j++) {
total_hours += content[j].hours;
}
if (total_hours < 35) {
sendMail(user[i]);
}
Logger.log("User name: " + users[i].display_name + " " + "User id: " + users[i].id + " " + "total hours: " + total_hours);
}

Cannot remove table after callback function is called

I'm trying to remove a table after some callback functions but table rows just keep getting inserted instead. I don't understand why the table is not being removed after the callbacks. I see that it actually calls the removeTable function and it knows that the table.length is more than 1 but nothing happens. Is it too quick or is it the way I'm doing ajax?
setInterval((function() {
showLeaders();
return showLeaders;
}()), 60000);
function showLeaders() {
uri = 'leaderboard.php'
ajaxLeaders(uri, callback);
setTimeout(function() {
uri = 'leaderboard.php';
ajaxLeaders(uri, callback2);
}, 15000);
}
function removeTable() {
// var table = document.getElementsByTagName('table'), index;
// console.log('im in the removeTable func '+table.length);
// for (index = table.length - 1; index >= 0; index--) {
// table[index].parentNode.removeChild(table[index]);
// }
Array.prototype.slice.call(document.getElementsByTagName('table')).forEach(
function(item) {
item.remove();
// or item.parentNode.removeChild(item); for older browsers (Edge-)
});
}
function ajaxLeaders(uri, callback) {
// console.log('ajaxLoad: ' + uri + ' - ' + params);
var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = callback;
request.open("POST", uri, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send();
// clearTimeout(ajax_failed_timer);
// ajax_failed_timer = setTimeout(ajaxError,20000);
}
var nameArray = [];
var totalPointsArray = [];
function callback(evt) {
var tables = document.getElementsByTagName('table');
console.log(tables.length);
if (tables.length >= 1) {
console.log('should remove table cause tables more than 1');
removeTable();
}
if (evt.currentTarget.readyState == 4) {
// console.log(evt.currentTarget.responseText);
var obj = JSON.parse(evt.currentTarget.responseText);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
nameArray.push(obj[key].username);
totalPointsArray.push(obj[key].total_points);
}
}
}
var bottomLeader = '';
var leaderPoints = '';
var leadersTable = '';
leadersTable = document.createElement('table');
var leadersHTML = '';
leadersHTML = '<tr>' +
'<th>Rank</th>' +
'<th>Username</th>' +
'<th>Points</th>' +
'</tr>';
for (var i = 0; i < totalPointsArray.length; i++) {
var rank = i + 1;
var infoBarEle = document.getElementById('info-bar-js');
leadersTable.className = 'animated flipInX';
/// sort width by hightest points
var maxPoints = Math.max.apply(Math, totalPointsArray);
leadersHTML +=
'<tr>' +
'<td>' + rank + '</td>' +
'<td>' + nameArray[i] + '</td>' +
'<td>' + totalPointsArray[i] + '</td>'
'</tr>';
var leaderType = document.getElementById('leaderType');
leaderType.innerHTML = 'Fantasy Football - Weekly Winners';
document.body.className = 'animated slideInRight';
}
leadersTable.innerHTML = leadersHTML;
insertAfter(leadersTable, infoBarEle);
function callback2(evt) {
var tables = document.getElementsByTagName('table');
if (tables.length >= 1) {
removeTable();
}
if (evt.currentTarget.readyState == 4) {
// console.log(evt.currentTarget.responseText);
var obj = JSON.parse(evt.currentTarget.responseText);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
nameArray.push(obj[key].username);
totalPointsArray.push(obj[key].total_points);
}
}
}
var bottomLeader = '';
var leaderPoints = '';
var leadersTable = '';
leadersTable = document.createElement('table');
var leadersHTML = '';
leadersHTML = '<tr>' +
'<th>Rank</th>' +
'<th>Username</th>' +
'<th>Points</th>' +
'</tr>';
for (var i = 0; i < totalPointsArray.length; i++) {
var rank = i + 1;
var infoBarEle = document.getElementById('info-bar-js');
leadersTable.className = 'animated flipInX';
/// sort width by hightest points
var maxPoints = Math.max.apply(Math, totalPointsArray);
leadersHTML +=
'<tr>' +
'<td>' + rank + '</td>' +
'<td>' + nameArray[i] + '</td>' +
'<td>' + totalPointsArray[i] + '</td>'
'</tr>';
var leaderType = document.getElementById('leaderType');
leaderType.innerHTML = 'Fantasy Football - Season Winners';
document.body.className = 'animated slideInRight';
}
leadersTable.innerHTML = leadersHTML;
insertAfter(leadersTable, infoBarEle);
}
//insertAfter function
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Make a selectable html table with objects as values

I am been trying to create a html table that is populated by objects.
The table was supposed to be selectable by row (via hover), when the row was hovered over a function ran.
The table headers are in an array:
var topTitles = ["Type","Origin","Destination","T","A","G"];
all the data are sitting inside arrays,
var Type = [];
var Origin = [];
var Destination = [];
var T = [];
var A = [];
var G = [];
I tried to modify an example piece of code, but it was very difficult to conceptualize it and place it into a programatic solution. What is an easy way to map such data directly into a interactive table.
function createTable() {
var table = document.getElementById('matrix');
var tr = addRow(table);
for (var j = 0; j < 6; j++) {
var td = addElement(tr);
td.setAttribute("class", "headers");
td.appendChild(document.createTextNode(topTitles[j]));
}
for (var i = 0; i < origins.length; i++) {
var tr = addRow(table);
var td = addElement(tr);
td.setAttribute("class", "origin");
td.appendChild(document.createTextNode(mode[i]));
for (var j = 0; j < topTitles.length; j++) {
var td = addElement(tr, 'element-' + i + '-' + j);
td.onmouseover = getRouteFunction(i,j);
td.onclick = getRouteFunction(i,j);
}
}
}
function populateTable(rows) {
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < rows[i].elements.length; j++) {
var distance = rows[i].elements[j].distance.text;
var duration = rows[i].elements[j].duration.text;
var td = document.getElementById('element-' + i + '-' + j);
td.innerHTML = origins[i] + "<br/>" + destinations[j];
}
}
}
if (highlightedCell) {
highlightedCell.style.backgroundColor="#ffffff";
}
highlightedCell = document.getElementById('element-' + i + '-' + j);
highlightedCell.style.backgroundColor="#e0ffff";
showValues();
}
This is probably the easiest way I could think of building the table without changing your data structure and make it very clear where all the data is coming from. It is defiantly not the best code, but it should work for your situation.
CodePen
var topTitles = ["Type","Origin","Destination","T","A","G"];
var Type = ["Type1", "type2", "type3"];
var Origin = ["Origin1", "origin2", "origin3"];
var Destination = ["Destination1", "Destination2", "dest3"];
var T = ["t1", "t2","T3"];
var A = ["steaksauce", "a2", "a3"];
var G = ["G1", "G2", "G3"];
var appendString = [];
for(var i =0; i < topTitles.length; i++){
if(!i){
appendString.push("<tr><td>" + topTitles[i] + "</td>");
}
else if(i === topTitles.length -1){
appendString.push("<td>" + topTitles[i] + "</td></tr>");
}
else{
appendString.push("<td>" + topTitles[i] + "</td>");
}
}
for(var i =0; i < Type.length; i++){
appendString.push("<tr><td>" + Type[i] + "</td><td>" + Origin[i] + "</td><td>" + Destination[i] + "</td><td>" + T[i] + "</td><td>" + A[i] + "</td><td>" + G[i] + "</td></tr>");
}
var table = document.getElementById('table');
table.innerHTML = appendString.join('');

Uncaught TypeError: Object [object Object] has no method 'tableRow' [duplicate]

This question already exists:
Update javascript table: Uncaught TypeError: Object [object Object] has no method 'tableRow'
Closed 9 years ago.
I'm creating a contacts book and wanting a table to update as the user inputs the data, but I keep getting this error about 'tableRow'. I've tried changing it to different function names etc. but can't seem to find the solutions.
var nameField, addressField, emailField, postcodeField;
function twoDigit(v){
if(v.toString().length < 2){
return "0"+v.toString();
} else {
return v.toString();
}
}
var Contact = function(name, address, email, postcode){
this.name = name;
this.address = address;
this.email = email;
this.postcode = postcode;
this.completed = false;
};
var contacts = [];
Contact.prototype.toString = function(){
var s = this.name + '\n' + this.address + '\n' + this.email + + '/n'
+ this.postcode.toString() + '\n';
if(this.completed){
s += "Completed\n\n";
} else {
s += "Not Completed\n\n";
}
return s;
};
Contact.prototype.tableRow = function(){
var tr = "<tr><td>" + this.name + "</td><td>" +
this.address + "</td><td>" + this.email +
"</td><td>" + this.address + ">";
};
var addContact = function(nameField, addressField, emailField, postcodeField){
a = new Contact(nameField.value, addressField.value, emailField.value,
postcodeField.value;
contacts.push(a);
};
var clearUI = function(){
var white = "#fff";
nameField.value = "";
nameField.style.backgroundColor = white;
addressField.value = "";
addressField.style.backgroundColor = white;
emailField.value = "";
emailField.style.backgroundColor = white;
postcodeField.value = "";
postcodeField.style.backgroundColor = white;
};
var updateList = function(){
var tableDiv = document.getElementById("table"),
table = "<table border='1'><thead><th>Name</th><th>Address</th>
<th>Email</th><th>Postcode</th><th>Completed</th></thead>";
for(var i=0, j=contacts.length; i<j; i++){
var contacts1 = contacts[i];
table += contacts1.tableRow();
}
table+="</table>";
tableDiv.innerHTML = table;
};
var add = function(){
addContact(nameField, addressField, emailField, postcodeField);
clearUI();
updateList();
};
var cancel = function(){
clearUI();
updateList();
};
window.onload = function(){
nameField = document.getElementById("name");
addressField = document.getElementById("address");
emailField = document.getElementById("email");
postcodeField = document.getElementById("postcode");
okButton = document.getElementById("ok");
okButton.onclick = add;
cancelButton = document.getElementById("cancel");
cancelButton.onclick = cancel;
clearUI();
};
var showTable = function(){
var tableDiv = document.getElementById("table"),
table = "<table border='1'><thead><th>Name</th><th>Address</th>
<th>Email</th><th>Postcode</th></thead>";
for(var i=0, j=contacts.length; i<j; i++){
var contacts1 = contacts[i];
table += contacts1.tableRow();
}
table+="</table>";
tableDiv.innerHTML = table;
};
Add a tableRow function to Contact
Contact.prototype.tableRow = function() {
return '<tr>' + '<td>' + this.name + '</td>' + '<td>' + this.address + '</td>' + '<td>' + this.email + '</td>' + '<td>' + this.postcode + '</td>' + '</tr>';
}

Categories