Save the Row data in Table using Javascript - javascript

Hi Here I am trying to save the data which user enter in a table. I have written Javascript for this.
<script type="text/javascript">
function Savefile() {
var tbl = document.getElementById("modaltable");
var final = " ";
var finalvalue = " ";
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++) {
var text = document.getElementById("Comment").value;
var typeofscram = document.getElementById("<%=DropDownList2.ClientID %>").value;
var scramblerreq = document.getElementById("<%=DropDownList1.ClientID %>").value;
var final = text + " " + typeofscram + " " + scramblerreq;
}
finalvalue += final;
}
}
var myCsv = finalvalue;
window.open('data:text/csv;charset=utf-8,' + escape(myCsv));
}
</script>
But it is saving only first row values. But I need to save the remaining row values also. In second row also it is saving first row details.Any mistake in above code.

Related

Assigning instances to my array (javascript). Whats causing this error?

I need to assign instances of my object as values in my array, but when I try to add let to my loop for collecting user input, I get an error stating that "[" is an unexpected token. This is a new technique to me so I'm not sure if this is even a practical method for making a table. Any help is appreciated.
<script>
function generateTable() {
var tblStart = "<table>";
//This is the header line for my table.
var tblMeat = "<tr> <td><b>Name</b></td> <td><b>Attendance</b></td> <td><b>Homework</b></td> <td><b>Midterm</b></td> <td><b>Final</b></td> <td><b>Course Grade</b></td> <td><b>Round Grade</b></td> <td><b>Letter Grade</b></td> </tr>";
var tblStop = "</table>";
//This determines the number of rows.
var rowCount = prompt("How many students are in the class?");
//I want to assign instances of Student to this array which will be used to fill the table cells.
var pupil = [NUMBER(rowCount)];
//This object should process user entries and use them to calculate the total grade, rounded grade, and letter grade.
function Student(name, attendance, homework, mGrade, fGrade) {
this.name = name;
this.attend = attendance;
this.homewrk = homework;
this.midter = mGrade;
this.fingrad = fGrade;
this.course = function () {
var attGrade = this.attend * 0.1;
var hwkGrade = this.homewrk * 0.2;
var midGrade = this.midter * 0.3;
var finGrade = this.fingrad * 0.4;
var combGrade = attGrade + hwkGrade + midGrade + finGrade;
return combGrade.toFixed(2);
};
this.round = Math.round(this.course);
this.letter = function() {
if(this.course < 60) {
return '<p style="color:red;">F</p>';
} else if(this.course >= 60 && this.course <= 69.9){
return "D";
} else if(this.course >= 70 && this.course <= 79.9) {
return "C";
} else if(this.course >= 80 && this.course <= 89.9) {
return "B";
} else if(this.course >= 90 && this.course <= 100) {
return "A";
};
};
}
/*This loop should collect user input based on the declared number of students, and assign input values to instances of
Student based on which execution of the loop is being run. I am getting an error stating "[" is unexpected for line 79.
*/
for (var r = 0; r < rowCount; r++) {
var studentN = prompt("Enter student name.");
var studentA = prompt("Enter student attendance.");
var studentH = prompt("Enter student homework grade.");
var studentM = prompt("Enter student midterm grade.");
var studentF = prompt("Enter student final grade.");
let pupil[r] = new Student(studentN, studentA, studentH, studentM, studentF);
}
for(var i = 0; i < rowCount; i++) {
tblMeat += "<tr>";
for(var j = 0; j < 8; j++) {
tblMeat += "<td>" + pupil[i].name + "</td><td>" + pupil[i].attend + "</td><td>" + pupil[i].homewrk + "</td><td>" + pupil[i].midter + "</td><td>" + pupil[i].fingrad + "</td><td>" + pupil[i].course() + "</td><td>" + pupil[i].round + "</td><td>" + pupil[i].letter() + "</td>";
}
tblMeat += "</tr>";
}
//This just puts it all together.
var completeTable = tblStart + tblMeat + tblStop;
document.getElementById("placetable").innerHTML = completeTable;
}
</script>
I ran your program through uglifyJS. It's actually for compressing javascript code, but when there is a lot of code to debug, it's a life changer.
The script told me:
Parse error: Unexpected token: punc ([)
Line 59, column 16
let pupil[r] = new Student(studentN, studentA, studentH, studentM, studentF);
You're trying to define an already existing variable. Remove "let".
A tiny advice for the future.

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);
}

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('');

Using the Date Object in an Array with Javascript

I need to display a date from an array and it needs to be incremented for each input by 1 day. The date should display as mm/dd/yyyy. I was able to get the date to display correctly with the code that is in the message but after each input the all the dates would increment. I need just the last input to increment a day and I thought putting it in an array would work but now nothing displays. Thanks for helping.
var lowTempArray = [];
var highTempArray = [];
var nowArray = [];
function process() {
'use strict';
//declare variables
var lowTemp = document.getElementById('lowTemp');
var highTemp = document.getElementById('highTemp');
var output = document.getElementById('output');
var date = new Date();
var message = ' ';
if (lowTemp.value) {
lowTempArray.push(lowTemp.value);
if (highTemp.value) {
highTempArray.push(highTemp.value);
message = '<table><th>Date </th><th> Low Temperatures</th><th> High Temperatures</th>';
for (var i = 0, count = lowTempArray.length; i < count; i++) {
for (var i = 0, count = highTempArray.length; i < count; i++) {
for (var i = 0, count = nowArray.length; i < count; i++) {
nowArray.push(new Date(date.getTime()));
date.setDate(date.getDate() + count);
message += '<tr><td>' + ((nowArray.getMonth() + 1) + '/' + (nowArray.getDate() + count) + '/' + nowArray.getFullYear()) + '</td><td> ' + lowTempArray[i] + '</td><td> ' + highTempArray[i] + '</td></tr>';
}
message += '</table>';
output.innerHTML = message;
}
}
}
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
} // End of init() function.
window.onload = init;

Categories