Assigning a function to an array of javascript buttons - javascript

When I click on of these button I want an item in sessionStorage to be assigned to true which is indicative of the button which was pressed. When the fourth button is clicked I was it to show what information was selected to know more about.
Right now my button aren't returning anything and I can't figure out how to loop through this and assign a function to every button
//simple html to print four buttons.
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript" src="example.js"></script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
document.getElementById(y[count].id).onclick = function(count) {
//Assigning a variable to be the id name of button passed into this function
z = y[arguments[i]].id;
//If the button is the fourth button
if ( z == "infoChosen" ){
//Add in the things which were selected
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
If the first button and then the fourth button is clicked the output should be
Green Molluscs
If the first and third button are clicked and then the fourth the output should be
Green Molluscs Green Sweaters
I need to do it in a loop

Try this
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript">
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
var aa = y[count].id;
document.getElementById(y[count].id).onclick = function(aa) {
var z = aa.currentTarget["id"];
if ( z == "infoChosen" ){
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
}
</script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>

I would do it differently in this situation.
In my eyes the best option is to make a function for each button like this <button onclick="myFunction()">Click me</button>and that function changes a variable too true or false. And when you click the 4th button it might be the best too use the switch statement for each possibility for the right output.
I am not that experienced in coding yet so this might not be the most efficient way but I hope this helped you.

Well, firstly, you're not accessing your sessionStorage correctly. See this. And what you're doing looks a bit like a mess. I've tidied up the code in my answer below so I'll just make some explanations here.
I decided to grab all your buttons using document.getElementsByTagName("button"); it may not always be applicable, but it feels suitable in your case.
I've changed using a for loop using length, to just using the of operator. It basically iterates through an array without needing to length it.
I think the other parts concerning putting stuff into the sessionStorage is pretty straight forward, but if you are unsure, just ask me and I'll rewrite it.
jsfiddle: https://jsfiddle.net/ryvcvp42/

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.

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>

We are analysing some code, I get what it is doing, but there is a line of code which I don't understand

This is the full code:
<html>
<head>
<script type='text/javascript'>
var banners = ["Red.jpg","Amber.jpg","Green.jpg"];
var bnrCntr = 0;
var timer;
function banCycle()
{
if(++bnrCntr == 3)
bnrCntr = 0;
document.images.banner.src = banners[bnrCntr];
timer = setTimeout("banCycle()",1000);
}
function stopCycle()
{
clearTimeout(timer);
}
</script>
</head>
<body>
<img src="Red.jpg" name="banner" width=110 height=200>
<form>
<input type="button" value="Cycle" name="Cycle" onclick="banCycle()">
<input type="button" value="Stop" name="Stop" onclick="stopCycle()">
</form>
</body>
</html>
It is the line that I don't understand:
if(++bnrCntr == 3)
Can anyone tell me what this line does?
The line
if (++bnrCntr == 3)
does the same thing as
if ((bnrCntr += 1) == 3)
or
bnrCntr = bnrCntr + 1;
if (bnrCntr == 3)
The value of bnrCntr is incremented, and the result is then assigned back to the variable. Then the value is compared to 3. The ++ operator is called the prefix increment operator.
It first increases the bnrCntr value by 1 and if that value equals to 3 it's set back to 0. You get circular banner changing this way. You could also write it this way, so it's more understandable:
if (++bnrCntr == banners.length)
bnrCntr = 0;
So, when the index goes out of the bounds of the array, start from the beginning.

Display click count and redirect to a url

I have found the below code to check the count of times the button has been clicked. However, I would like the button to redirect to an URL once it is clicked and update the click count.
<html>
<head>
<title>Increment count when button is clicked</title>
</head>
<body>
<input type="button" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
count++;
display.innerHTML = count;
}
</script>
</body>
</html>
button.onclick = function(){
count++;
display.innerHTML = count;
window.location = "http://jonathanmh.com";
}
This would do the trick, but nobody would ever see the number, because it simply goes away, after the user is redirected to another page. If you want to save the number for other users to see, you need to save it on the server and preferably in a database.
To achieve that you need to store click count in cookie or localStorage (or anywhere else where your data persists):
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
if (isNaN(localStorage.yourCounter))
localStorage.yourCounter = 0;
localStorage.yourCounter++;
display.innerHTML = localStorage.yourCounter;
window.location = 'http://jsfiddle.net/'
}

Categories

Resources