issues with a global array and sending json data - javascript

var x = document.getElementsByTagName('button');//return button array
//arrays
var entry_age = [];//age
var entry_relation = [];//relation
var entry_smoker = [];//smoker
//add button clicked
x[0].addEventListener("click", function(){
var age = document.getElementsByName("age")[0].value;//pull age from box
var relation = document.getElementsByName("rel")[0].value;//pull relation
let smoker = document.querySelector('[name=smoker').checked;
//check relation
if(relation === "")
{
alert("please select a realation");
}
//check to see if age < 0
if(age < 0 || age === " ")
{
alert("age not applicable");
}
//add data to arrays
entry_age.push(age);
entry_relation(relation);
entry_smoker(smoker);
alert(entry_age[0]);
});
x[1].addEventListener("click", function(){
var age = JSON.stringify(entry_age);
alert(entry_age[1]);
document.getElementbyClassName("debug").innerHTML = JSON.stringify(entry_relation);
document.getElementByClass("debug").innerHTML = JSON.stringfy(entry_smoker);
});
I'm trying to store a value in entry age dynamically and convert that to JSON and display it in a only thing is I can't get the data to store in the array, how do I get the array to work globally? At this point I'm pretty sure it's my array but do y'all see anything wrong with the JSON. For debugging purposes I used an alert with the array index and the one in the second function is coming up as unidentified It is to return to a pre tag with the class name of debug. You guys have really helped me out a lot with this project.

Related

How to make my Array to be empty again and reusable for my Edit Text Function

Newbie here.. I was making an expense note app(just a noob app). I have this button function on which when I select one table row.. It will be deleted and the table row input text value will return to the input bar text area(name, date, amount, remarks). I was happy when it work.
But it only work once.
Because when I select different table row data. It will be deleted but the same "first input data value" will always return to the input text bar..
It seems the first table data are being saved in the empty array function that can be reuse again. What I am hoping for is when I use the empty array function it will be empty again to be use in another different table row data.
I am using array methods but failed or my If statement is wrong. Hopefully you can answer this :) thanks
document
.getElementById("editSelection")
.addEventListener("click", editSelection);
function editSelection() {
var editName = [];
var editDate = [];
var editAmount = [];
var editRemarks = [];
let selectedRows = document.getElementsByClassName("selected-row ");
while (selectedRows.length > 0) {
editName.push(cell0.innerText);
editDate.push(cell1.innerText);
editAmount.push(cell2.innerText);
editRemarks.push(cell3.innerText);
selectedRows[0].parentNode.removeChild(selectedRows[0]);
var name = document.getElementById("inputName");
name.value = editName.join("\n");
var date = document.getElementById("inputDate");
date.value = editDate.join("\n");
var amount = document.getElementById("inputAmount");
amount.value = editAmount.join("\n");
var remarks = document.getElementById("inputRemarks");
remarks.value = editRemarks.join("\n");
}
if (name || date || amount || remarks) {
editName.splice([0], editName.length);
editDate.splice([0], editDate.length);
editAmount.splice([0], editAmount.length);
editRemarks.splice([0], editRemarks.length);
}
}
If you define an empty array
var editName = [];
and fill it with values you can empty it again with
editName = [];

Else statement still running when if statement is true with google script

I have a function that has a name with a set of data and this name is compared to a list of names. If that name is already in the list of names, the data associated with the name replaces the old data. If the name is a name not in the list of names it adds the name and the associated info to the bottom of the list.
For some reason when I run the code with a name already in the list, the original data is replaced and the name and data are added to the bottom of the list. I want to avoid repeating people while also adding new individuals.
var app = SpreadsheetApp;
var activeSheet = app.getActiveSpreadsheet();
var lookup = app.getActiveSpreadsheet().getSheetByName("Lookup");
var issued = app.getActiveSpreadsheet().getSheetByName("Issued");
var name1 = lookup.getRange(12,3).getValue();
var info = lookup.getRange(16,3,1,12).getValues();
for (var j=1;j<105;j++){
var issuedOfficers = issued.getRange(j,11).getValue();
//if the officers name is already recorded in issued the system will replace the current data with updated data
if (issuedOfficers === name1){
issued.getRange(j,1,1,12).setValues(info);
} else {
var lastrow = issued.getLastRow();
issued.getRange(lastrow+1,1,1,12).setValues(info);
break;
}
}
}```
How about this modification?
Modification points:
In your script,
When j is 1 and issuedOfficers === name1 is true, issued.getRange(j,1,1,12).setValues(info) is run. And, when j is 2 and issuedOfficers === name1 is false, issued.getRange(lastrow+1,1,1,12).setValues(info) is run. And the for loop is finished.
When j is 1 and issuedOfficers === name1 is false, issued.getRange(lastrow+1,1,1,12).setValues(info) is run. And the for loop is finished.
I think that this is the reason of your issue. In order to avoid this issue, how about the following modification?
Modified script:
From:
for (var j=1;j<105;j++){
var issuedOfficers = issued.getRange(j,11).getValue();
//if the officers name is already recorded in issued the system will replace the current data with updated data
if (issuedOfficers === name1){
issued.getRange(j,1,1,12).setValues(info);
} else {
var lastrow = issued.getLastRow();
issued.getRange(lastrow+1,1,1,12).setValues(info);
break;
}
}
To:
var names = issued.getRange(1, 11, 105, 1).getValues().flat();
var index = names.indexOf(name1);
if (index > -1) {
issued.getRange(index + 1,1,1,12).setValues(info);
} else {
issued.appendRow(info[0]);
}
In this modification, at first, the values are retrieved from the sheet of issued, and it checks whether name1 is included in the values. By this, the row is updated or the value is appended.
Note:
Please use this script with enabling V8.
References:
flat()
indexOf()
appendRow(rowContents)

Having Trouble Accessing the Value of a Score stored in Local Storage

I'm having issues when trying to access the value of a score that is stored in the localStorage from a variable that is equal to how many questions the user gets right. I thought it would be exactly the same as setting the value but most likely I've done something wrong, and I lack the experience to figure it out..
I Want to display the User's score on the screen's scoreboard where the complete button is. I easily set the score into the localStorage with the setItem(users, score) line, but it seems getItem(score) doesn't work when I want to set displayUser.textContent = getItem(score).
I've tried a lot of different ways, and I always get null. I also noticed every time I submit a new entry to the scoreboard, the key's name keeps the last entries name and stores it on the end.
I'd love to fix this myself, but after making no progress or any leads for 3 hours, I think I might ask for some help. I reused and changed a lot of this code from a class activity in my boot camp so the complete button is just there to remove entries while in development.
Here's all of the relevant JavaScript hopefully
//Variables to Shorten text
var startButton = document.getElementById('startbtn')
var nextButton = document.getElementById('nextbtn')
var finishEarlyButton = document.getElementById('finishEarlyBtn')
var introSection = document.getElementById('intro')
var questionSection = document.getElementById('Question-Section')
var questionElement = document.getElementById('question')
var answerButtons = document.getElementById('Answer-Section')
var scoreboard = document.getElementById('Score-Container')
var userScore = document.getElementById('Score')
var seeScoreBtn = document.getElementById('seeScore')
var restartBtn = document.getElementById('restart')
var finishbtn = document.getElementById('finishbtn')
var userAnswer = ""
var shuffledQuestions, currentQuestionIndex
var score = 0
var userName = document.getElementById('scoreboard-input')
var leaderboard = document.getElementById('leaderboard')
var leaderboardUsers = document.getElementById('leaderboardUsers')
var users = [];
init();
function init() {
var storedUsers = JSON.parse(localStorage.getItem("Users"))
if (storedUsers !== null) {
users = storedUsers;
renderUsers();
}
}
function renderUsers() {
leaderboardUsers.innerHTML = "";
for (var i = 0; i < users.length; i++) {
var user = users[i];
var li = document.createElement("li");
li.textContent = user;
li.setAttribute("data-index", i);
var button = document.createElement("button");
button.textContent = "Complete";
var displayUser = document.createElement("button");
displayUser.textContent = (localStorage.getItem(score));
//displayUser.textContent = "test";
console.log(localStorage.getItem(users.value))
li.appendChild(displayUser);
li.appendChild(button);
leaderboardUsers.appendChild(li);
}
}
function storeUsers() {
//localStorage.setItem("users", JSON.stringify(users));
//localStorage.setItem(JSON.stringify(users), JSON.stringify(score));
localStorage.setItem(users, score);
}
leaderboard.addEventListener("submit", function() {
event.preventDefault();
var userText = userName.value.trim();
var userCorrectAnswers = score.value;
if (userText === "") {
return
}
//users.push(userCorrectAnswers);
users.push(userText);
userName.value = "";
storeUsers()
renderUsers()
console.log
})
leaderboardUsers.addEventListener("click", function(event) {
var element = event.target;
if (element.matches("button") === true) {
var index = element.parentElement.getAttribute("data-index");
users.splice(index, 1);
storeUsers();
renderUsers();
}
})
Let me know if the html or rest of JS is needed!
Well just by looking at the code we can see that you're accessing it via
var storedUsers = JSON.parse(localStorage.getItem("Users"))
and storing it via
localStorage.setItem(users, score);
With the way you're accessing it, you would set it via
localStorage.setItem("Users", JSON.stringify(users));
It is case-sensitive, which is probably why your attempt of using the key users didn't work in your first comment under your storeUsers function.
This is a lot of code to sift through but setting and getting items requires string key-names and stringified values:
localStorage.setItem('users', JSON.stringify(score))
JSON.parse(localStorage.getItem('users'))
This way you should have the same data before and after setting to localStorage.
You are not using localStorage setItem correctly.
localStorage.setItem(users, score);
Both arguments to setItem() must be strings, with the first argument a key, and the second argument the value to store. Your first argument is an array (the data type of your second argument is unclear).
Typical value of a setItem first argument: 'usersScores'.
localStorage.setItem('usersScores', JSON.stringify(score));
Note the use of JSON.stringify() to convert score to a string, because localStorage only stores data in string form.
You are also not using getItem correctly:
localStorage.getItem(score)
getItem must be called with the key used in setItem:
localStorage.getItem('userScores')
And since score was saved as a string, you need to convert it back when you read it from localStorage:
score = JSON.parse(localStorage.getItem('userScores'))
How to use localStorage is explained clearly in MDN web docs Using the Web Storage API.

How to create a for loop to loop through JSON.stringified values determining "paste tabs" for values

Update: I need to check if a unique value is already in the pasteTab's appropriate column. My code for that is --
for (a = 0; a<coldChainRange.length;a++){
var fillWeeks = coldChainRange[a][12]
**var rxNumbers = coldChainRange[a][0]**
var pasteTab = ss.getSheetByName(fillWeeks)
//var range = pasteTab.getRange('A2:P'+pasteTab.getLastRow()).getDisplayValues()
**var array = [];
array.push(rxNumbers)**
Logger.log(array)
//Logger.log(fillWeeks)
if(fillWeeks != "Need Days Supply"){
if (pasteTab !== null && **array.indexOf(pasteTab[a][0]==-1**)){
var patientInfo = ([coldChainRange[a][0],coldChainRange[a][1],coldChainRange[a][2],coldChainRange[a][3],coldChainRange[a][4],
coldChainRange[a][5],coldChainRange[a][6],coldChainRange[a][7],coldChainRange[a][8],coldChainRange[a][9],
coldChainRange[a][10],coldChainRange[a][11],coldChainRange[a][12],coldChainRange[a][13],coldChainRange[a][14]])
pasteTab.appendRow(patientInfo)
}
}
}
}
I need to have the info not be appended if a number is already in the column, however I think the loop is iterating the length of the "pasteTab" which is determined by a week number which is two characters long
How can I create a loop that will go read JSON.stringifed values?
I am trying to loop through cell values to determine where the information should be appended to. For example, if a cell had a value of "23" it would be appended to the 23 tab.
function sendToFillWeek() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var coldChainPasteSheet = ss.getSheetByName('from looker')
var coldChainRange = coldChainPasteSheet.getRange('A2:P' + coldChainPasteSheet.getLastRow()).getDisplayValues()
for (a = 0; a<coldChainRange.length;a++){
var fillWeeks = JSON.stringify(coldChainRange[a][12])
var pasteTab = ss.getSheetByName(fillWeeks)
Logger.log(pasteTab)
}}
This is my code so far for determining the appropriate sheet. The fillWeeks produces the values I need, however the pasteTab outputs all "null" values.
for(b=0; b<fillWeeks.length;b++){
(if fillWeeks !== "Need Day Supply" ){
var patientInfo = ([coldChainRange[a][0],coldChainRange[a][1],coldChainRange[a][2],coldChainRange[a][3],coldChainRange[a][4],
coldChainRange[a][5],coldChainRange[a][6],coldChainRange[a][7],coldChainRange[a][8],coldChainRange[a][9],
coldChainRange[a][10],coldChainRange[a][11],coldChainRange[a][12],coldChainRange[a][13],coldChainRange[a][14],
coldChainRange[a][15]])
pasteTab.appendRow(patientInfo)
}
}
}
}
Essentially, I would like the information to be appended the appropriate tabs.

Find specific line in CSV based on 2 values with Javascript

I am trying to search, find and fetch some data from a CSV file using HTML/PHP/Javascript.
I want to make a form with 2 dropdowns, one for the FROM Zone name and one for the TO Zone name, and use the Zone codes (102, 104, 105 etc) as values for the dropdown items.
After the user have selected the FROM and TO i want to display the single digit to the far right (col 5).
Example: User choose "Zone1" to "Zone4", then the number "4" should be returned.
FromZoneCode;FromZoneName;ToZoneCode;ToZoneName;Distance;;;;
101;zone1;101;zone1;1;;;;
101;zone1;104;zone4;4;;;;
101;zone1;105;zone5;5;;;;
104;zone4;101;zone1;4;;;;
104;zone4;105;zone5;2;;;;
104;zone4;104;zone4;1;;;;
I have tried to search for a solution for this but i cant seem to find the right info.
Worked out after a long time:
Don't know how you got the CSV data. In the following example, I got it by an ajax request.
No jQuery needed.
Created the dropdowns dynamically.
Set the variable delimeter to ; (or) , as required, because most CSV files contains CSV delimeter.
Give the names of the columns for which dropdowns to be created in the variables dropdownname1 and dropdownname2.
Give the name of the column to be displayed as result on chaning dropdowns in the variable resultname.
Create a <span> element with id="result" in the HTML to display the result.
Variable keys contains column names.
Variable values contains array of arrays as values.
var data = [];
$.ajax({
url:"/Users/Default/Downloads/test.csv",
type:"GET",
datatype:"csv",
success:function(response){
data = response.split(/\r\n/);
start();
}
});
//Logic starts here
//Initializations
var keys = [], values = [], delimiter = ";";
var dropdownname1 = "FromZoneName", dropdownname2 = "ToZoneName", resultname = "Distance";
var resultelem = document.getElementById("result");
//Functionalities
function createDropdown(field)
{
function createOption(option, isselected)
{
var optionelem = document.createElement("option");
optionelem.value=option;
optionelem.text=option;
optionelem.selected = isselected;
return optionelem;
}
var selectelem = document.createElement("select");
selectelem.setAttribute("id",field);
var insertedoptions = [];
for(var i=0;i<values.length;i++)
{
var option = values[i][keys.indexOf(field)];
if(insertedoptions.indexOf(option) == -1)
{
insertedoptions.push(option);
selectelem.appendChild(createOption(option));
}
}
selectelem.appendChild(createOption("",true));
return selectelem;
}
function start()
{
keys = data.splice(0,1)[0].split(delimiter);
values = [];
for(var i=0,n=data.length;i<n;i++)
{
values.push(data[i].split(delimiter));
}
var bodyelem = document.getElementsByTagName("body")[0];
bodyelem.appendChild(createDropdown(dropdownname1));
bodyelem.appendChild(createDropdown(dropdownname2));
document.getElementById(dropdownname1).addEventListener("change",displayData);
document.getElementById(dropdownname2).addEventListener("change",displayData);
}
function displayData()
{
var selectelem1 = document.getElementById(dropdownname1), selectelem2 = document.getElementById(dropdownname2);
var selectedvalue1 = selectelem1.value, selectedvalue2 = selectelem2.value;
for(var i=0,n=values.length;i<n;i++)
{
if(values[i][keys.indexOf(dropdownname1)] == selectedvalue1 && values[i][keys.indexOf(dropdownname2)] == selectedvalue2)
{
resultelem.innerHTML=values[i][keys.indexOf(resultname)];
break;
}
else
{
resultelem.innerHTML="";
}
}
}

Categories

Resources