Issue with Revealing Individual Images & Ending Loop - javascript

Since my last question, I've decided to reveal images individually. However, now I'm having an issue with the sequence. With what I've written so far, it seems that my second needed image (stack2.PNG) appears before the first (stack1.PNG). Also, I'm not too sure how to go about ending the function after the final image (stack3.PNG).
Here's what I have so far:
<body>
<input type=button value="Produce Stipends" onclick="nextStack()"/>
<img id="stipends" src="nostack.PNG">
</body>
<script>
var stipends = document.getElementById("stipends");
var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"];
var currentStack = 0;
stack.forEach(function(src) {
new Image().src = src;
});
function nextStack() {
currentStack++;
currentStack > 2 && (currentStack = 0);
stipends.src = stack[currentStack];
}
</script>
Also, if it's not too much to ask, how would I go about changing the name of the button once the sequence is over and linking to another page.
Thanks in advance!

Run the below code if you want to output a single index of the stack array on each click.
EDIT: Included comments in code.
var stipends = document.getElementById("stipends");
var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"];
//currentStack = 0 starts the index at 0
//we will use this to iterate over the array in sequential order starting with the first item
var currentStack = 0;
function nextStack() {
//declare array length as a var
var len = stack.length;
//on click, check if currentStack value is less than len
if(currentStack < len){
//console log the item in the stack array that has a matching index
console.log(stack[currentStack]);
//apply the same output as image source
stipends.src = stack[currentStack];
//continue adding to the currentStack for the next loop until finished
currentStack++;
}
}
<input type=button value="Produce Stipends" onclick="nextStack()" />
<img id="stipends" src="nostack.PNG">

Is this what you're trying to do?
var stipends = document.getElementById("stipends");
var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"];
var currentStack = 0;
function nextStack() {
currentStack++;
stipends.src = stack[currentStack];
if (currentStack > stack.length) {
currentStack = 0;
}
}
<input type="button" value="Produce Stipends" onclick="nextStack()"/>
<img id="stipends" src="nostack.PNG">

Related

How to validate an user answer button click javascript

Currently I'm trying to create a quiz, right now it displays the first question with 4 answer choices after the start button I am stuck on how to retrieve the answer. The user clicks, check to see if its correct and loop to the next question. I just want to give the user one chance per question and move on regardless if it's correct or not. If their answer is wrong I will remove seconds from the timer. I have the questions, answer choices, and correct answers in arrays.
<div class="card-body">
<p id="header">
You have 75 seconds to complete this asessment.
Every incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
<script src="./script.js"></script>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"],
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime --;
timerEl.textContent = totalTime;
if(totalTime === 0){
clearInterval(timerInterval);
endQuiz();
return;
}
}, 1000);
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
console.log(i);
return;
}
}
Hi I will try to provide an easy solution to your question without using any kind of difficult javascript syntax so here goes..
First in your html file update the option button and add a class property called clickOption(you can change the class name if you want, but be sure to change in other places in script.js as well). The code is shown below.
<button id="option0" class="clickOption" data-index="0"></button><br>
<button id="option1" class="clickOption" data-index="1"></button><br>
<button id="option2" class="clickOption" data-index="2"></button><br>
<button id="option3" class="clickOption" data-index="3"></button><br>
Now in your script.js file add the line of code shown below. I have added inline comments for better understanding
// get all elements with class clickoption i.e all option buttons
var elements = document.getElementsByClassName("clickOption");
//use the below array to track the selected answers
var selectedAnswers = [];
var clickOption = function() {
/** Here I have reached the end of the test and,
I am logging the array of user-selected options.
This array can be compared with correctAnswers array
to determine whether the answer is correct or not **/
if(questionNum >= questions.length) {
console.log(selectedAnswers);
return;
}
/**Get the option value that was clicked.
Here I am using parseInt because,
the data-index attribute value will be in string format,
and the correctAnswers array is in Number format so it is better,
to keep the selectedAnswers array in Number format as it will faciliate
easier data comparison**/
var selectedOption = parseInt(this.getAttribute('data-index'));
// add the selected option to the selectedAnwsers Array
selectedAnswers.push(selectedOption);
/** here I am assuming that you are using the questionNum variable
to track the current question Number **/
questionNum += 1;
/** here I am again checking if I have reached the end of test and
thus log the answers
Instead of logging the answer you can create a function
that compares the result and display it on screen **/
if(questionNum >= questions.length) {
console.log(selectedAnswers);
return;
}
// update the next question text
questionEl.textContent = questions[questionNum];
// update next options
displayQuestion(questionNum);
}
//loop through all the elements with class clickOption
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', clickOption);
}
start.addEventListener("click", function() {
timer();
/** I have updated the displayQuestion call implementation
so that the function is called with a parameter
(here the parameter it is zero) **/
displayQuestion(questionNum);
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
/**Finally I have updated the display question method
so that it updates the option buttons based on the index parameter **/
function displayQuestion(index){
questionEl.textContent = questions[index];
option0.textContent = answers[index][0];
option1.textContent = answers[index][1];
option2.textContent = answers[index][2];
option3.textContent = answers[index][3];
}
Hope this solution helps you. Happy Coding!

How to Show Next/Previous item of an array?

I'm writing the first item of an array to the screen, and would like to create Next/Previous buttons for array, but I can't get it to work. I have tried several methods, but I can't find suitable solution.
Can anyone help?
This is the last one I have tried:
var data = [
{"subject":"starcraft2",
"date":"08.31",
"dDay":"mon",
"content1":"STARCRAFT2",
"content2":"season2",
"playerA":"Ju",
"playerB":"Lee",
"emblemA":"Terran",
"emblemB":"Zerg",
"result":"end"},
{"subject":"starcraft2",
"date":"08.29",
"dDay":"wed",
"content1":"STARCRAFT2",
"content2":"season2",
"playerA":"kim",
"playerB":"joo",
"emblemA":"Terran",
"emblemB":"Protoss",
"result":"end"},
];
function prevAction() {
// function (e) { // the e here is the event itself
alert("Prev Click!");
// document.getElementById('subject').textContent = prevItem();
// document.getElementById('date').textContent = prevItem();
for (var i = 0; i<data.length; i++)
for (var j=0; j<data[i]; j++)
while(j === 0)
{
j == j++;
console.log(j);
}
console.log(data[j].date + ', ');
document.getElementById('date').textContent = data[j].date;
// document.getElementById('subject').textContent = j[0];
}
Here's the jist of how you'd accomplish this in pure Javascript:
getNextItem() {
var index = document.getElementById("index").value;
//add guards here to prevent array overflow/underflow
if (data.length < index - 1) {
index.value++;
}
document.getElementById("DOM_ELEMENT_TO_ATTACH_DATA").innerHTML = data[index];
}
getPreviousItem() {
var index = document.getElementById("index").value;
//add guards here to prevent array overflow/underflow
if (index > 0) {
index.value--;
}
document.getElementById("DOM_ELEMENT_TO_ATTACH_DATA").innerHTML = data[index];
}
<input id="index" type="hidden" name="index" value="0">
<button type="button" onclick="getNextItem()">Next Item</button>
<button type="button" onclick="getPreviousItem()">Previous Item</button>
Note that this will just attach the pure json data to a DOM element, it won't do anything fancy with it.
Furthermore, if you want to do anything more complex, I'd strongly recommend you look into using a library like jQuery or Angular as it's going to make your life a whole lot easier in the long run.

Get second, third and so on values

I have this problem here
The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense.
Thank you!
Kind regards,
L.E. Test file
If I understood your question correctly, instead of breaking the loop when a match to "Total" is found do whatever is needed to be done within the loop like so...
var today = toDateFormat(new Date());
var todaysColumn =
values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1",
"dd/MM/yyyy");
for (var i=0; i<values.length; i++){
if (values[i][0]=='Total'){
nr = i;
Logger.log(nr);
var output = values[nr][todaysColumn];
// Do something with the output here I"m assuming you email it
}
}
The loop will keep going and find every "Total" and do the same thing. This answer assumes that the "Totals" are in the same column. You can get fancier with this if you only want certain tables to send and not others, but this should get you started.
I didn't quite understand the second part of your question...
"Also, is there any solution to automatically find the the array
number which contain date row for each table (instead defining this
manually). Hope my explanation make sense."
I'm guessing you want all the rows that contain "Total" in the specific column. You could instantiate a variable as an empty array like so, var totals = [];. Then instead of sending the email or whatever in the first loop you would push the row values to the array like so, totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0). You could then simply loop through the totals array and do whatever you wanted to do. Alternatively you could create an array of all the values instead of row numbers like totals.push(values[nr][todaysColumn]) and loop through that array. Lots of ways to solve this problem!
Ok based on our conversation below I've edited the "test" sheet and updated the code. Below are my edits
All edits have been made in your test sheet and verified working in Logger. Let me know if you have any questions.
Spreadsheet:
Added "Validation" Tab
Edited "Table" tab so the row with "Email Address" in Column A lines up with the desired lookup values (dates or categories)...this was only for the first two tables as all the others already had this criteria.
Code:
Create table/category selector...
In the editor go to File >> New >> HTMLfile
Name the file "inputHTML"
Copy and paste the following code into that file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
<select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
<p></p>
<select id="categories" style="display:none"></select>
<hr/>
<button class="submit" type="submit">Get Total</button>
</form>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// The code in this function runs when the page is loaded.
$(function() {
var tableRunner = google.script.run.withSuccessHandler(buildTableList);
var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
tableRunner.getTables();
catagoryRunner.getCategories();
});
function buildTableList(tables) {
var list = $('#tables');
list.empty();
list.append('<option></option>');
for (var i = 0; i < tables.length; i++) {
if(tables[i]==''){break;}
list.append('<option>' + tables[i] + '</option>');
}
}
function buildCatagoryList(categories) {
var list = $('#categories');
list.empty();
list.append('<option></option>');
for (var i = 0; i < categories.length; i++) {
if(categories[i]==''){break;}
list.append('<option>' + categories[i] + '</option>');
}
}
function hideunhideCatagory(tableValue){
var catElem = document.getElementById("categories");
if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
catElem.style.display = "none"
document.required = false;
}else{
catElem.style.display = "block"
document.required = true;
}
}
function formSubmit(argTheFormElement) {
var table = $("select[id=tables]").val(),
catagory = $("select[id=categories]").val();
console.log(table)
google.script.run
.withSuccessHandler(google.script.host.close)
.getTotal(table,catagory);
}
</script>
</body>
<div id="hiframe" style="display:block; visibility:hidden; float:right">
<iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
</div>
</html>
Edits to Code.gs file
Replace code in Code.gs with this...
//This is a simple trigger that creates the menu item in your sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Scripts Manually')
.addItem('Get Total','fncOpenMyDialog')
.addToUi();
}
//This function launches the dialog and is launched by the menu item
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Select table to get total for');
};
//main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
function getTotal(table,catagory) {
function toDateFormat(date) {
try {return date.setHours(0,0,0,0);}
catch(e) {return;}
}
//get all values
var values = SpreadsheetApp
.openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
.getSheetByName("Tables")
.getDataRange()
.getValues();
//declare/instantiate your variables
var tableHeaderRow, totalRow, tableFound = false;
//begin loop through column A in Tables Sheet
for (var i = 0; i<values.length; i++){
//test to see if values have already been found if so break the loop
if(tableFound == true){break;}
//check to see if value matches selected table
if (values[i][0]==table){
//start another loop immediately after the match row
for(var x=i+1; x<values.length; x++){
if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
tableHeaderRow = x;
tableFound = true;
}else if(values[x][0] == "Total"){
totalRow = x;
break;
}
}
}
}
Logger.log("Header Row = "+tableHeaderRow)
Logger.log("Total Row = "+ totalRow)
var today = toDateFormat(new Date())
var columnToTotal;
if(catagory==''){
columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
}else{
columnToTotal = values[tableHeaderRow].indexOf(catagory);
}
var output = values[totalRow][columnToTotal];
Logger.log(output);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");
//here is where you would put your code to do something with the output
}
/** The functions below are used by the form to populate the selects **/
function getTables(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var tabelCol = (cSheetHeader.indexOf("Tables")+1);
var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
return tables.filter(function (elem){
return elem != "";
});
}
function getCatagories(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
return catagories.filter(function (elem){
return elem != "";
});
}

Having trouble with onchange and storing numbers in an array via textbox

I am having trouble with my onchange not working and storing numbers in an array via a text box.
What I want the code to do is to get statistics on the numbers inputted into the text box. I do this by having the user input numbers into the text box and hit the Enter key to display those numbers. The numbers should be put into an array before being put into a list to display the inputted numbers. However, I keep getting this error where the onchange is not triggering when hitting the Enter key or clicking off of the text box.
Here is an image of the error I am getting when inspecting the code
With the numbers stored in the array, I want to try to get the Mean of the numbers. But, I keep getting the error "NaN" which makes me think that my numbers are not getting stored into the array properly.
Here is the code:
<html>
<head>
<title>Stats</title>
</head>
<p>Array is called numbers. numbers.sort();</p>
<div id="stats">
<input type ="text" id="value" onchange="list()"> <!-- Getting the Onchange Error here -->
<button id="button1" onclick = "list()">Enter</button>
<ul id="list1">
</ul>
<button id="stat_button" onclick="calculateMean()">Get Statistics</button>
<p id="mean">Mean= </p>
</div>
<script>
function list() {
var liElement = document.createElement("li"); //Creating new list element//
var ulElement = document.getElementById("list1"); //Get the ulElement//
var input = document.getElementById("value").value; //Get the text from the text box//
var numbers = []; //create Array called numbers
numbers.push(input);//adds new items to the array
//for loop//
for(var i=0; i < numbers.length; i++) {
liElement.innerHTML = numbers[0]; //Puts the array into the list for display//
ulElement.appendChild(liElement); //add new li element to ul element//
}
}
function calculateMean() {
var meanTotal = 0;
var meanAverage = 0;
var meanArray = [];
for (var i = 0; i < meanArray.length; i++) {
meanTotal += meanArray[i];
}
meanAverage = (meanTotal / meanArray.length);
document.getElementById("mean").innerHTML = meanAverage;
}
</script>
Try adding it through addEventListener instead of inline like that:
document.getElementById('value').addEventListener('change', function(e){
list()
})
The reason the Mean is always NaN is because your mean array is always an empty array when you start with. I think you were referring to a numbers array here.
You will have to declare the array outside the scope of the 2 functions, since it is the common to both.
And it is always a better idea to decouple Javascript and HTML. Bind your events in JS instead of inline event handlers.
Note: When you read the value from the input, it is a string, so convert it to a number before storing it in the numbers array.
HTML
<p>Array is called numbers. numbers.sort();</p>
<div id="stats">
<input type="text" id="value">
<!-- Getting the Onchange Error here -->
<button id="button1">Enter</button>
<ul id="list1">
</ul>
<button id="stat_button">Get Statistics</button>
<p id="mean">Mean= </p>
</div>
JS
document.getElementById('value').addEventListener('change', list);
document.getElementById('button1').addEventListener('click', list);
document.getElementById('stat_button').addEventListener('click', calculateMean);
var numbers = [];
function list() {
var liElement = document.createElement("li"); //Creating new list element//
var ulElement = document.getElementById("list1"); //Get the ulElement//
var input = document.getElementById("value").value; //Get the text from the text box//
numbers.push(input); //adds new items to the array
//for loop//
for (var i = 0; i < numbers.length; i++) {
liElement.innerHTML = numbers[0]; //Puts the array into the list for display//
ulElement.appendChild(liElement); //add new li element to ul element//
}
}
function calculateMean() {
var meanTotal = 0;
var meanAverage = 0;
for (var i = 0; i < numbers.length; i++) {
meanTotal += numbers[i];
}
meanAverage = (meanTotal / numbers.length);
document.getElementById("mean").innerHTML = meanAverage;
}
jsFiddle

Passing array -- scope

I want to pass an array from one external .js file to another.
Each of these files works fine by themselves, but I am having a problem passing the array from pickClass.js to displayStudent.js, and getting the names and "remaining" value to display in the html file. I know it has something to do with how the arrays are declared, but I can't seem to get it to work properly.
The first file declares the array choice:
(masterStudentList.js):
var class1 = ['Brown, Abe','Drifter, Charlie','Freed, Eve'];
var class2 = ['Vole, Ug','Xylo, William','Zyzzyx, Yakob'];
The second picks which array to use based on the radio buttons (pickClass.js):
var classPicked = array(1);
function randomize(){
return (Math.round(Math.random())-0.5); }
function radioResult(){
var chooseClass = document.getElementsByName("chooseClass");
for (i = 0; i < chooseClass.length; i++){currentButton = chooseClass[i];
if (currentButton.checked){
var selectedButton = currentButton.value;
} // end if
} // end for
var output = document.getElementById("output");
var response = "You chose ";
response += selectedButton + "\n";
output.innerHTML = response;
chosenClass = new Array();
if (selectedButton == "class1")
{chosenClass = class1;}
else
{chosenClass = class2;}
var text = "";
var nametext = "";
var i;
for (i = 0; i < chosenClass.length; i++) {
text += chosenClass[i]+ ' / ';
}
var showText = "";
l = chosenClass.length;
classPicked = Array(l);
for (var i = 0; i < l; ++i) {
classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
showText += classPicked[i]+ '<br>';
}
//return = classPicked;
document.getElementById("classList").innerHTML = classPicked;
} // end function
This works properly.
I then want to pass "classPicked" to another .js file (displayStudent.js) which will randomize the student list, loop and display the students for a few seconds, and then end with one student name.
basket = classPicked; //This is where the array should be passed
function randOrd(){
return (Math.round(Math.random())-0.5); }
function showBasket(){
mixedBasket = basket.sort( randOrd ); //randomize the array
var i = 0; // the index of the current item to show
document.getElementById("remaining").innerHTML = basket.length;
fruitDisplay = setInterval(function() {
document.getElementById('showStud')
.innerHTML = mixedBasket[i++]; // get the item and increment
if (i == mixedBasket.length) i = 0; // reset to first element if you've reached the end
}, 100); //speed to display items
var endFruitDisplay = setTimeout(function()
{ clearInterval(fruitDisplay);
var index = mixedBasket.indexOf(document.getElementById('showStud').innerHTML);
mixedBasket.splice(index,1);
}, 3500); //stop display after x milliseconds
}
Here is the html (master.html). It's just rough -- I'll be working on the layout later:
<html>
<head>
<script src="masterStudentList.js" type="text/javascript"></script>
<script src="pickClass.js" type="text/javascript"></script>
<script src="displayStudent.js" type="text/javascript"></script>
</head>
<body>
<h2>Choose Class</h2>
<form action = "">
<fieldset>
<input type = "radio"
name = "chooseClass"
id = "radSpoon"
value = "class1"
checked = "checked" />
<label for = "radSpoon">Class 1</label>
<input type = "radio"
name = "chooseClass"
id = "radFlower"
value = "class2" />
<label for = "radFlower">Class 2</label>
<button type = "button"
onclick = "radioResult()"> Choose Class
</button>
<div id = "output">
</fieldset>
</form>
</div>
<center>
<h1> <span id="chooseStud"></span><p></h1>
<script> var fruitSound = new Audio();
fruitSound.src = "boardfill.mp3";
function showFruitwithSound()
{
fruitSound.play(); // Play button sound now
showBasket()
}
</script>
Remaining: <span id = "remaining" ></span>
<p>
<button onclick="showFruitwithSound()">Choose Student</button>
</center>
pickedClassList = <p id = classList> </p>
</body>
</html>
You shouldn't use global variable like this (I encourage you to read more on this theme) and I'm not sure I understand what you're trying to do... but the solution of your issue should be to move the basket = classPicked; line into your showBasket method :
basket = classPicked; //This is where the array should be passed
function randOrd(){
return (Math.round(Math.random())-0.5);
}
function showBasket(){
// whatever
}
should be :
function randOrd(){
return (Math.round(Math.random())-0.5);
}
function showBasket(){
basket = classPicked; //This is where the array should be passed
// whatever
}
This way, each time you call showBasket, this method will use the last value of classPicked.
Otherwise, basket will always keep the reference on the first value of classPicked.
Why ? because each time you assign a new Array to the basket variable (classPicked = Array(l);) instead of changing directly it's content by :
emptying it : while (classPicked.length > 0) { classPicked.pop(); }
and then adding new data : classPicked.concat(chosenClass)
You can't pass things to files; you could call a function defined in displayStudent.js, pass it classPicked, and have it assign it to basket.
I noticed this at the end of your second chunk of code ...
} // end function
This could indicate the classPicked is declared inside a function (I don't see one on the code). Because it is inside function scope, your set of code that is trying to use it cannot.
Push the declaraction of classPicked outside of the function.
var classPicked = Array(1);
function thisusesclasspicked() {
...
Also, please start indenting your code properly, it will become much easier to maintain and read.
UPDATE FROM COMMENTS:
I see the declaration now ...
classPicked = Array(l);
for (var i = 0; i < l; ++i) {
classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
showText += classPicked[i]+ '<br>';
}
... however, you are re-assigning the array with an element of one just before you attempt to make modifications to it ... You are emptying it there: classPicked = Array(l);

Categories

Resources