Javascript, make a variable inside a function globally available - javascript

this application has 2 select functions, the first select function takes data from a json file. when one is selected it saves the ID in a variable. this variable is created using let outside the function. in the second select function it takes data from a json file and only shows the data where the ID from the json matches the ID saved in the first select variable.
The problem is that the variable cant be found outside of the function. when i console the variable outside the function it came back undefined
I tried changing the variable from let to var. this didn't work. i expected it to be solved but instead there didn't happen anything diffrent.
let locID;
let select;
let select2;
function preload() {
data = loadJSON(
"https://raw.githubusercontent.com/mia-mmt2-2223/leesfestival/main/festival.json"
);
}
function setup() {
createCanvas(400, 400);
//LOCATION SELECTION
//create select element with as options name from locations from json
select = createSelect();
select.position(10, 10);
select.option("Select a location");
for (let i = 0; i < data.locations.length; i++) {
select.option(data.locations[i].name);
}
//when a location is selected, save the location id
select.changed(function () {
item = select.value();
for (let i = 0; i < data.locations.length; i++) {
if (data.locations[i].name == item) {
locID = data.locations[i].id;
}
}
});
//WORKSHOP SELECTION
//create select element with as options name from workshops where location matches locID from json
select2 = createSelect();
select2.position(10, 50);
select2.option("Select a workshop");
for (let i = 0; i < data.workshops.length; i++) {
if (data.workshops[i].location == locID) {
select2.option(data.workshops[i].name);
}
}
}````

Related

how to display the value of an array using innerHTML?

I have an array n i have a four buttons n I just want to display array values ,if i click on first button ,first value should be displayed ,click on second button ,second value should be displayed n so on using addEventListener event handler but there is a problem when i click it directly display last value?
var element = document.querySelectorAll('.box1');
var city = document.querySelector('#name');
for (var i = 0; i < element.length; i++) {
element[i].addEventListener('click', function () {
var i = 0;
var places = ['San diago,USA', 'chicago,USA', 'phoenix,USA', 'New york,USA'];
while (i <places.length) {
console.log(city.innerHTML = places[i]);
i++;
}
});
}
You were iterating over the list of buttons, then inside each handler were also iterating over the full list (using the same variable i). Each button only needs one handler, so you only need one loop.
I moved your "Cities" array outside the function, there's no reason to define it separately inside each handler.
const places = ['San diego,USA', 'chicago,USA', 'phoenix,USA', 'New york,USA'];
let element = document.querySelectorAll('.box1');
let city = document.querySelector('#name');
for (let i = 0; i < element.length; i++) {
element[i].addEventListener('click', function() {
city.innerHTML = places[i];
});
}
<button class="box1">One</button>
<button class="box1">Two</button>
<button class="box1">Three</button>
<button class="box1">Four</button>
<div id="name"></div>
Take special note of the use of let i instead of var i inside that for loop -- ES6 variables are scoped differently; if I had used var there then all four events would get the value of i after the loop has run (so all the buttons would be looking for places[4]!). With let or const the variable is scoped within its block, so the value you want is captured by each iteration in the loop.

Issue with linking values from pre-defined list to data argument

I am programming a task-switching experiment in javascript using the jsPsych library (jsPsych 6.0.5). I use a predefined list with stimulus attributes but I can't seem to link the specific values to variables in the data argument (output of data is undefined).
I am using a for-loop to link these values to the data argument, but that doesn't seem to be working. In the sample here below the first for-loop reads in the different columns of the predefined list, with each row representing a single trial. In the second for-loop, I try to input these values for each trial (row) to the data argument of my test_stimuli
for(this_trial = 0; this_trial < blocks[0].length; this_trial ++){
curr_trial = blocks[0][this_trial];
modality[this_trial] = curr_trial[6];
cresp[this_trial] = curr_trial[10];
perc_stim[this_trial] = [];
for(j = 0; j < 4; j++){perc_stim[this_trial][j] = curr_trial[11 + j];};
probe[this_trial] = curr_trial[15];
condition[this_trial] = curr_trial[16];
}
for (i = 0; i < blocks[0].length; i++) {
test_stimuli[i] = [{
image: `<img src="images_a/${perc_stim[i][0]}.bmp" class = "training1"/>`,
data: {
correct_response: [cresp[i]],
modality: modality[i],
trial_id: 'stim'
}
}];
}
When I log the data argument to the console, I get "undefined" (even though it logs the correct values when looking at for example the cresp array).

Pre-fill form with local storage

I'm loading questions from a JSON into my EJS template and want to populate each field from localStorage. The following saves the last value of each dropdown, text, and slider element:
var select = document.getElementsByTagName('select');
for (var i = 0; i < select.length; i++){
select[i].value = localStorage.getItem(i);
}
jQuery("select").change(function () {
for (var i = 0; i < select.length; i++){
localStorage.setItem(i, select[i].value);
}
});
I repeat this for all "input" tags. The issue is that the select values also get passed into text and slider — and vice versa (i.e. if I enter values for text and slider, they overwrite the select values, except they are left blank).
My end goal is to save each form-fields' most recent value so that my entries are not lost when I refresh the page.
It would be a lot more elegant to create a single localStorage entry representing your saved values, rather than pollute LS with many entries for each field. I would recommend something like this:
function save() {
const selects = document.querySelectorAll('select');
// select other element types
// ...
const selectValues = [...selects].map(select => select.value);
const textValues = [...textInputs].map(textInput => textInput.value);
const sliderValues = [...sliderInputs].map(sliderInput => sliderInput.value);
const savedObj = { selectValues, textValues, sliderValues };
localStorage.savedFormValues = JSON.stringify(savedObj);
}
That way, you only create a single entry in localStorage, and each entry type is quite distinct. Then, to get the values, just do the same thing in reverse:
function populate() {
const selects = document.querySelectorAll('select');
// ...
const { selectValues, textValues, sliderValues } = JSON.parse(localStorage.savedFormValues);
selectValues.forEach((selectValue, i) => selects[i].value = selectValue);
// ...

associative array not setting correctly

i'm new to javascript and jquery and was wondering if someone could let me in on why this isn't working correctly.
i have a drop-down box that a user selects a value from, then "Processes." When processed the value of the drop-down as well as a textbox is stored in an array. I want the user to be able to then basically store the same drop-down selection and textbox data in the array again but now in a new value pair.
First store would be
TestArray[0][0] = "Textbox Value"
If "Processed" again, it would be
TestArray[1][0] = "Textbox Value"
that way I can parse through later and figure how many times the user "Processed" the drop-down selection;
var oneClickReport = $("#reportName").val();
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
But when trying to "Process" for the second time, I receive the error of;
SCRIPT5007: Unable to set property '0' of undefined or null reference
on line;
arrayTest[arrayOneCount][totalHouseholds] = HHName;
You need to initialize your array. I'm not sure what exactly you want to do but you need an array like this
var arrayTest = []
And you will need to initialize subsequent value like
arrayTest[1] = []
Then you can access your array
arrayTest[1][0] = []
I made an example for you
var oneClickReport = $("#reportName").val();
var arrayTest = [] # You may need to put this elsewhere
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
if(!arrayTest[arrayOneCount]){ arrayTest[arrayOneCount] = []; }
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
your problem with var arrayOneCount = reportOneArray.length; and you're not changing this value

extract elements from two arrays with same value

Hello I want to extract elements from both arrays with the same url .How can i loop these two arrays and get their content, because it gives me undefined for the news_url and i think it outputs twice the items in the console.
function geo(news_array,user_tweets){
console.log(news_array,user_tweets);
for (var x=0; x<user_tweets.length; x++) {
var user = user_tweets[x].user;
var date = user_tweets[x].date;
var profile_img = user_tweets[x].profile_img;
var text = user_tweets[x].text;
var url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
function second(user,date,profile_img,text,url){
for (var i = 0; i < news_array.length; i++) {
var news_user = news_array[i].news_user;
var news_date = news_array[i].news_date;
var news_profile_img = news_array[i].news_profile_img;
var news_text = news_array[i].news_text;
var news_url=news_array[i].url;
if (url==news_array[i].news_url) {
geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url);
}
}
}
function geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url) {
console.log(url,news_url);
}
}
The problem is
in news_tweets function, you add news_url to news_array. So you should call
news_array[i].news_url
in second function.
I modify your code as
news_url: (item.entities.urls.length > 0)?item.entities.urls[0].url : '' in news_tweets function
add close brace } for geo function and remove } from last
add new_array parameter to second function like second(user, date, profile_img, text, url,news_array);
Modify code can be tested in http://jsfiddle.net/rhjJb/7/
You have to declare some variables before the first for loop, so that they can be accessed in the scope of the second function. Try to replace your first for loop with the following code:
var user, date, profile_img, text, url;
for (var x=0; x<user_tweets.length; x++){
user = user_tweets[x].user;
date = user_tweets[x].date;
profile_img = user_tweets[x].profile_img;
text = user_tweets[x].text;
url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
Moreover, in the if of your second function, news_array[i].news_url isn't defined. Use if (url == news_url) instead.

Categories