Javascript, saving values from onclick and saving previous values in arrays - javascript

i'm trying to save values retrieved from "onclick" and also save the values previously retrieved from "onclick" in different arrays when buttons are clicked.
but it seems like when "for loop" is used, newly retrieved values overwrite previously retrieved data even though those values are saved separately in different arrays.
i'm really confused right now, does anybody know why?
(if you hit the button "refresh", you can see the current values that are saved.)
var firstValue = [];
var preValue = [];
function returneD(a){
preValue = firstValue;
console.log("returned! preValue: "+preValue);
for (var i = 0; i < 1; i++) {
firstValue[i] = a;
console.log("returned! firstValue: "+firstValue);
}
}
function refresh1(){
console.log("preValue: "+preValue);
console.log("firstValue: "+firstValue);
}
<!DOCTYPE html>
<html>
<head>
<script src="jstest.js"></script>
</head>
<body id="thebody">
<button id="1" onclick="returneD(this.id)">O N E</button>
<button id="2" onclick="returneD(this.id)">T W O</button>
<button id="3" onclick="returneD(this.id)">T H R E E</button>
<button id="4" onclick="returneD(this.id)">F O U R</button>
<br>
<button onclick="refresh1()">refresh</button>
</body>
</html>

Please refer this code will work,
firstValue is array which already stored value after that this will assign old value to preValue array.
var firstValue = [];
var preValue = [];
function returneD(a){
preValue = a;
console.log("returned! preValue: "+preValue);
for (var i = 0; i < 1; i++) {
firstValue[i] = a;
console.log("returned! firstValue: "+firstValue);
}
}
function refresh1(){
console.log("preValue: "+preValue);
console.log("firstValue: "+firstValue);
}
<!DOCTYPE html>
<html>
<head>
<script src="jstest.js"></script>
</head>
<body id="thebody">
<button id="1" onclick="returneD(this.id)">O N E</button>
<button id="2" onclick="returneD(this.id)">T W O</button>
<button id="3" onclick="returneD(this.id)">T H R E E</button>
<button id="4" onclick="returneD(this.id)">F O U R</button>
<br>
<button onclick="refresh1()">refresh</button>
</body>
</html>

In JavaScript Arrays are just like Objects. When you assign:
preValue = firstValue; this simply takes a reference to the variable hence you fail to copy the value.
In order to achieve that, you need to copy each value of that array to the previous values array. So, you can run another for loop for first to previous assignment:
for (var i = 0; i < 1; i++) {
prevValue[i] = firstValue[i];
}
Assuming they are of the same size.

Related

Sharing a variable between HTML JavaScript functions

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function wordRand(){
var words = ["DOG", "CAT", "MOUSE", "GIRAFFE"];
return words[Math.floor(Math.random()*words.length)];
}
function replaceAt(str,index,chr){
if(index > str.length-1)
return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
function wordSet(){
var i, word=wordRand();
document.getElementById("text").innerHTML += word.charAt(0); //places the first letter.
for(i=1;i<word.length;i++)
document.getElementById("text").innerHTML += '-';
document.getElementById("checkword").innerHTML = word; //my current solution.
}
function check(letter){
//variable "word" receives the string from the paragraph with ID "checkword".
var exists=false, i, word=document.getElementById("checkword").innerHTML, correct;
for(i=1;i<word.length;i++){
if(word.charAt(i)==letter){
exists=true;
correct = document.getElementById("text").innerHTML;
correct = replaceAt(correct, i, letter);
document.getElementById("text").innerHTML = correct;
}
}
if(exists==false)
document.getElementById("verify").innerHTML += "No ";
}
</script>
</head>
<body onload="wordSet();">
<p id="text"></p>
<p id="verify">Mistakes: </p>
<div id="keyboard">
<button onclick="check('Q');">Q</button>
<button onclick="check('W');">W</button>
<button onclick="check('E');">E</button>
<button onclick="check('R');">R</button>
<button onclick="check('T');">T</button>
<button onclick="check('Y');">Y</button>
<button onclick="check('U');">U</button>
<button onclick="check('I');">I</button>
<button onclick="check('O');">O</button>
<button onclick="check('P');">P</button>
<button onclick="check('A');">A</button>
<button onclick="check('S');">S</button>
<button onclick="check('D');">D</button>
<button onclick="check('F');">F</button>
<button onclick="check('G');">G</button>
<button onclick="check('H');">H</button>
<button onclick="check('J');">J</button>
<button onclick="check('K');">K</button>
<button onclick="check('L');">L</button>
<button onclick="check('Z');">Z</button>
<button onclick="check('X');">X</button>
<button onclick="check('C');">C</button>
<button onclick="check('V');">V</button>
<button onclick="check('B');">B</button>
<button onclick="check('N');">N</button>
<button onclick="check('M');">M</button>
</div>
<!--word saver, for functions (which I want to get rid of)-->
<p id="checkword" style="visibility:hidden;"></p>
</body>
</html>
I'll start off by saying that I apologize if this question is extremely basic and probably has been already answered, but I can't seem to find a proper response to it:
I am in the process of creating the code for an HTML page, with a bit of JavaScript included. However, I have a problem with a variable: my only way to pass it is by first inserting its content in an element inside the body, and then copying it in the other function's variable, as follows:
function parolaSet(){
var i;
var parola=parolaRand();
document.getElementById("testo").innerHTML += parola.charAt(0);
for(i=1;i<parola.length;i++)
document.getElementById("testo").innerHTML += '-';
document.getElementById("verifica").innerHTML = parola;
}
function check(lettera){
var present=false, i, parola=document.getElementById("verifica").innerHTML, giusto;}
Where "verifica" is a "p" element. I did think about using the simple "return parola;" command in the parolaSet function, however, this function sets a word in the HTML page that can't be changed by any means, as it's a requirement for my project to work. Making the call everytime I need a returned value from it would reset the word and mess everything up. So, is there another way to share this value without having to use up space in the page, repeating the parolaSet function's code and just by using common JavaScript functions and commands? If JavaScript on its own is not enough for this, I would like to acknowledge other options anyway.
P.S. Creating a global variable doesn't seem to work, as the value is returned as an "Object object" when used in the page or inside of functions.
EDIT: Due to absolutely reasonable suggestions, I added a snippet of my page. It's all just a basic hangman game, the words in the original code are much more, but this is the most minimal I could make it.
Try a hidden input field to pass the value along with every web request.
Somthing like:
<input hidden id="MyValueToPass" value="parola">
Have a look at this
I delegate the click and have word as a global
let word;
function wordRand() {
var words = ["DOG", "CAT", "MOUSE", "GIRAFFE"];
return words[Math.floor(Math.random() * words.length)];
}
function replaceAt(str, index, chr) {
if (index > str.length - 1)
return str;
return str.substring(0, index) + chr + str.substring(index + 1);
}
function wordSet() {
word = wordRand(); // set the global word
document.getElementById("text").innerHTML = word.charAt(0) + word.slice(1).replace(/./g,"-")
}
function check(letter) {
//variable "word" receives the string from the paragraph with ID "checkword".
var exists = false, i, correct;
for (i = 1; i < word.length; i++) {
if (word.charAt(i) == letter) {
exists = true;
correct = document.getElementById("text").innerHTML;
correct = replaceAt(correct, i, letter);
document.getElementById("text").innerHTML = correct;
}
}
if (exists == false)
document.getElementById("verify").innerHTML += "No ";
}
window.addEventListener("load", function() {
document.getElementById("keyboard").addEventListener("click", function(e) {
const tgt = e.target.closest("button");
if (tgt)
check(tgt.textContent)
})
wordSet();
});
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="text"></p>
<p id="verify">Mistakes: </p>
<div id="keyboard">
<button>Q</button>
<button>W</button>
<button>E</button>
<button>R</button>
<button>T</button>
<button>Y</button>
<button>U</button>
<button>I</button>
<button>O</button>
<button>P</button>
<button>A</button>
<button>S</button>
<button>D</button>
<button>F</button>
<button>G</button>
<button>H</button>
<button>J</button>
<button>K</button>
<button>L</button>
<button>Z</button>
<button>X</button>
<button>C</button>
<button>V</button>
<button>B</button>
<button>N</button>
<button>M</button>
</div>
<!--word saver, for functions (which I want to get rid of)-->
<p id="checkword" style="visibility:hidden;"></p>
</body>
</html>

Javascript array change in realtime after button click

i'm making a web application which helps people to seek what disease they have according to the symptoms.
I want to the user to click specific symptom to add in the "u_symptom_i" array and show all of the changed array elements by alert function
However, i cannot see the added element by alert function
<script>
var j = 0;
while(j < escaped_cc.length) {
document.write('<th><button id="symptom_button">' + escaped_cc[j] + '</button></th>');
document.getElementById("symptom_button").value = escaped_cc[j];
j = j + 1;
}
$("button").click(function() {
u_symptom_i.push($(this).val());
alert($(this).val());
});
</script>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<h2>Insert Array</h2>
<input type="text" id="example" name="value">
<button id="button">Add array new item</button>
</body>
<script>
var array=[];
$("#button").click(function() {
var str = $("#example").val();
array.push(str);
alert(array);
});
</script>
</html>
Can you try this code? Adds each new value entered to an array named array and displays the records.

Use sessionstorage to store the values in an array

Please help. I need my array to save when I goto another page. Since the page refreshes it loses the array. From here my code stops at the beginning of the store it function when I try to use sessionstorage.
Here is my attempt. The array part is just to remove the duplicate from and array and place it into array b.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Session Storage Attempt</title>
<script src="untitled-1.js" type="text/javascript"></script>
</head>
<body>
<button onClick="doIt()">Button</button>
<br>
<br>
<button onClick="storeIt()">Store It</button>
</body>
</html>
Javascript:
let a = [];
let b = [];
function doIt(){
a.push("a");
let len = a.length;
for(let i = 0; i < len; i++){
if(b.indexOf(a[i]) === -1){
b.push(a[i]);
}
}
alert(b);
}
function storeIt(){
sessionStorage.setItem('bee', JSON.stringify(b));
JSON.parse(sessionStorage.getItem('bee'));
alert(bee);
}

Javascript Function to setTimeout and when a button on page is clicked cancel the timeout and proceed with the remaining functions?

<!DOCTYPE HTML>
<HTML>
<head>
<center>
<b> This is My Virtual Pet!</b>
</center>
<center> <img id="target" src="https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431" width="300" height="250" />
<br>
<input type="button" onclick="changeImage()" value=" Scroll Through Emotions" /> </center>
<br>
<center>
<input type="button" onclick="TimeoutStop()" onclick="changeImage(this)" data-values="1,2" value="Feed">
<input type="button" onclick="TimeoutStop()" onclick="changeImage(this)" data-values="3,4,5" value="Pet">
<input type="button" onclick="TimeoutStop()" onclick="changeImage(this)" data-values="3,0,4" value="Play">
</center>
<script>
var target = document.getElementById('target');
var counter = 0;
var myVar;
var myRhino = [
"https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431",
"https://img04.deviantart.net/0594/i/2010/261/5/6/happy_rhino_by_ammut88-d2z0sto.jpg",
"https://images.fineartamerica.com/images-medium-large-5/angry-rhino-daniel-eskridge.jpg",
"https://c2.staticflickr.com/2/1340/1368093048_fa7ef85a5a_z.jpg?zz=1",
"https://images.fineartamerica.com/images/artworkimages/mediumlarge/1/hungry-rhino-james-sarjeant.jpg",
"http://m.rgbimg.com/cache1nulfB/users/z/za/zatrokz/600/meRoKDQ.jpg",
"https://i.ytimg.com/vi/R_zz1GEkEk4/maxresdefault.jpg",
];
myVar = setTimeout("TimeoutImg()",2000);
function changeImage(btn) {
if (!btn) {
counter += 1;
target.src = myRhino[counter % myRhino.length];
} else {
var data = btn.getAttribute('data-values');
var pics = JSON.parse("[" + data + "]"); // Convert string of numbers to an array
var num = pics.shift(); // remove index 0 from array and store it in num
pics.push(num); // Add what was previously at index 0 to end of array
target.src = myRhino[num];
counter = num;
btn.setAttribute('data-values', pics.join(','));
}
}
function TimeoutImg(){
target.src = myRhino[6];
}
function TimeoutStop(){
clearTimeout(myVar);
}
</script>
</head>
<body>
</body>
</HTML>
This is the new code with the timeout function. How come when I click the button the timeout stops but It doesn't let me change any pictures on click.
I am trying to have the picture change in 10 seconds after the page opens if no buttons are clicked but if a button is clicked have the timer stop and proceed normallyy by clicked each of the three action buttons and having the image change.
You only need one function to achieve this. Firstly, you can create a function which is in charge of changing the pictures, which you currently have. In my example below I called this changeImage. This function can accept this as an argument, which refers to the current button you clicked on.
onclick="changeImage(this);" // When button is clicked, go to image at index 2
By using this we can get the button's attributes such as the data-values attribute I defined on your buttons.
<input type="button" onclick="changeImage(this)" data-values="1,2" value="Feed">
The data-values attribute allows you to specify the images you want to go to on each image click and the order in which it should follow. I made the data-values attribute work by:
Converting the string value to an array of numbers. Eg: "1,2" turns into [1, 2]. This allows me to manipulate the values easily.
Using this array, I then get the value at index 0 using .shift(). This removes the value at index 0 and also returns it. After using .shift() my array now looks like:
[2].
However, because I used .shift() I was able to store the deleted value in num, which I use as the index for the image to display.
I then use .push() to push the deleted value (or num) back onto the end of my array. So it now looks like [2, 1].
Lastly, I updated the data-values attribute to be equal to this new array. I use .join(',') on the array to turn it into "2,1", and then use .setAttribute to update my data-values attribute. So my element now looks like:
<input type="button" onclick="changeImage(this)" data-values="2,1" value="Feed">
Now, if I click on the button again, I will repeat this cycle, and the image displayed will be 2 and the data-values attribute will be updated to data-values="1,2" again.
However, if a button isn't passed through into the function, (detected by using if(!btn)), then you can simply just change the image based on the counter.
See working example below:
<!DOCTYPE HTML>
<HTML>
<head>
<center>
<b> This is My Virtual Pet!</b>
</center>
<center> <img id="target" src="https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431" width="300" height="250" />
<br>
<input type="button" onclick="changeImage()" value=" Scroll Through Emotions" /> </center>
<br>
<center>
<input type="button" onclick="changeImage(this)" data-values="1,2" value="Feed">
<input type="button" onclick="changeImage(this)" data-values="3,4,5" value="Pet">
<input type="button" onclick="changeImage(this)" data-values="3,0,4" value="Play">
</center>
<script>
var target = document.getElementById('target');
var counter = 0;
var myRhino = [
"https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431",
"https://img04.deviantart.net/0594/i/2010/261/5/6/happy_rhino_by_ammut88-d2z0sto.jpg",
"https://images.fineartamerica.com/images-medium-large-5/angry-rhino-daniel-eskridge.jpg",
"https://c2.staticflickr.com/2/1340/1368093048_fa7ef85a5a_z.jpg?zz=1",
"https://images.fineartamerica.com/images/artworkimages/mediumlarge/1/hungry-rhino-james-sarjeant.jpg",
"http://m.rgbimg.com/cache1nulfB/users/z/za/zatrokz/600/meRoKDQ.jpg",
"https://i.ytimg.com/vi/R_zz1GEkEk4/maxresdefault.jpg",
];
function changeImage(btn) {
if (!btn) {
counter += 1;
target.src = myRhino[counter % myRhino.length];
} else {
var data = btn.getAttribute('data-values');
var pics = JSON.parse("[" + data + "]"); // Convert string of numbers to an array
var num = pics.shift(); // remove index 0 from array and store it in num
pics.push(num); // Add what was previously at index 0 to end of array
target.src = myRhino[num];
counter = num;
btn.setAttribute('data-values', pics.join(','));
}
}
</script>
</head>
<body>
</body>
</HTML>
As you've edited your question to a new question, I'll post an additional answer.
The reason as to why your timer isn't working is because you have a few issues with your code:
myVar = setTimeout("TimeoutImg()",2000); isn't correct, your first argument for setTimeout should be a function callback, not a string. Here you've almost got it right, you just need to change your string to the function callback:
var myVar = setTimeout(TimeoutImg, 2000);
Also, generally in programming, it's not considered "good practice" to name your functions with capital letters at the start (as you use capitals for classes/objects). So from now on, I will use lowercase letters at the start of each function name.
Another issue is how you are stopping the timeout interval. You've
got the right idea with having onlcick trigger the timeoutStop
function, however, you're not going about it the right way. A HTML
element should only have no repeated attributes on it, so in your
case, you're repeating onclick twice:
onclick="timeoutStop()" onclick="changeImage(this)"
Instead, of having two onclick attributes, you can combine these into one:
onclick="changeImage(this); timeoutStop()"
Fixing these issues will resolve your issue.
See working example below:
<!DOCTYPE HTML>
<HTML>
<head>
<center>
<b> This is My Virtual Pet!</b>
</center>
<center> <img id="target" src="https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431" width="300" height="250" />
<br>
<input type="button" onclick="changeImage()" value=" Scroll Through Emotions" /> </center>
<br>
<center>
<input type="button" onclick="changeImage(this); timeoutStop()" data-values="1,2" value="Feed">
<input type="button" onclick="changeImage(this); timeoutStop()" data-values="3,4,5" value="Pet">
<input type="button" onclick="changeImage(this); timeoutStop()" data-values="3,0,4" value="Play">
</center>
<script>
var target = document.getElementById('target');
var counter = 0;
var myRhino = [
"https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431",
"https://img04.deviantart.net/0594/i/2010/261/5/6/happy_rhino_by_ammut88-d2z0sto.jpg",
"https://images.fineartamerica.com/images-medium-large-5/angry-rhino-daniel-eskridge.jpg",
"https://c2.staticflickr.com/2/1340/1368093048_fa7ef85a5a_z.jpg?zz=1",
"https://images.fineartamerica.com/images/artworkimages/mediumlarge/1/hungry-rhino-james-sarjeant.jpg",
"http://m.rgbimg.com/cache1nulfB/users/z/za/zatrokz/600/meRoKDQ.jpg",
"https://i.ytimg.com/vi/R_zz1GEkEk4/maxresdefault.jpg",
];
var changeImageTimer = setTimeout(timeoutImg, 5000); // 5 second timer
function changeImage(btn) {
if (!btn) {
counter += 1;
target.src = myRhino[counter % myRhino.length];
} else {
var data = btn.getAttribute('data-values');
var pics = JSON.parse("[" + data + "]"); // Convert string of numbers to an array
var num = pics.shift(); // remove index 0 from array and store it in num
pics.push(num); // Add what was previously at index 0 to end of array
target.src = myRhino[num];
counter = num;
btn.setAttribute('data-values', pics.join(','));
}
}
function timeoutImg() {
target.src = myRhino[myRhino.length-1];
}
function timeoutStop() {
clearTimeout(changeImageTimer);
}
</script>
</head>
<body>
</body>
</HTML>

Hidden input field

I have an array with 8 elements defined within a script.
I'd like to know how I can pass all the values of this array to a single hidden element.
Pls help.
<script ='text/javascript'>
function abc(){
var arr= new Array(8);
for (var i=0; i<8;i++)
{
arr[i]= ...;
}
</script>
<input type="hidden" id="arrs" name="arrs" value= ? >
you can join them with comma ','
$('#arrs').val(arr.join(','));
From the comments on the question itself
I will have to access this input
hidden element in another js later on
using document.forms.element(''). so
thought it would be easier using a
single element.
It would be easiest to not use any form element at all. Not sure why you want to take such a detour. You have a JavaScript variable, you can use that directly in "another script later on":
<script type="text/javascript" id="firstScript">
function abc(){
var arr = [];
for (var i=0; i<8; i++) {
arr.push(...);
}
return arr;
}
var myArray = abc();
</script>
<!-- time passes, but we're still on the same page... -->
<script type="text/javascript" id="anotherScript">
doSomethingWith(myArray);
</script>
You can try like this:
<script>
function a(){
var arr= new Array(8);
for (var i=0; i<8;i++)
{
arr[i]= i;
}
document.getElementById('d').value = arr;
alert(document.getElementById('d').value);
}
</script>
<input id="d" type="hidden" />
<input type="button" onclick="javascript:a();" value="A" />
Hope this helps.
If the values are only strings or integers, you can try joining them with a seperator not present in your input:
document.getElementById("arrs").value = arr.join("###");
And you can do
myArr = document.getElementById("arrs").value.split("###");
To retreive that array back.

Categories

Resources