HTML button with different output onclick using JavaScript - javascript

I have the following setup - http://codepen.io/anon/pen/WvjmLv?editors=100 and am trying to output text depending on which button is clicked
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="right-answer" type="button">6</button>
<button class="wrong-answer" type="button">10</button>
<script>
var text;
var wrongAnswer = document.getElementsByClassName("wrongAnswer").addEventListener("click");
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click");
if (wrongAnswer) {
text = "Incorrect!";
text = "Wrong!";
text = "Try Again!";
}
if (rightAnswer) {
text = "Correct!";
}
document.getElementById("answer").innerHTML = text;
</script>
</div>
<div>
<p id="answer"></p>
</div>
If the user selects the wrong answer, it should either read Wrong!, Incorrect! or Try Again! (without repeating the same text output if their next guess is also wrong)
If they get the answer right, it should just simply read Correct!
As I'm fairly new to JavaScript, I feel as though I'm a little bit off with my solution and was wanting to know how can I make this function work?
Thanks.

Easiest and fastest way to get the result you want is by adding onclick-eventhandlers to your buttons.
<button onclick="somefunction()"></button>
After that you can easily handle what should happen after that click.
In your case I would check what's in the class attribute of the button you clicked.
By doing this you can print the results to your #answer-container.
With a simple array and a global variable of which index is next you can output different "false"-messages.
var _i = 0;
var _wrongs = ['Incorrect!', 'Wrong!', 'Try Again!'];
function showResult(b) {
var res = document.getElementById('answer');
if (b.classList.contains('right-answer')) {
res.innerHTML = 'Correct'
} else {
res.innerHTML = _wrongs[_i];
_i = _i > 1 ? 0 : _i + 1;
}
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" onclick="showResult(this)">2</button>
<button class="wrongAnswer" onclick="showResult(this)">5</button>
<button class="right-answer" onclick="showResult(this)">6</button>
<button class="wrong-answer" onclick="showResult(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
Demo on Codepen

Well, there are a couple things that you need to do:
You do not have a separate click handler function defined.
You need to properly add the event function to the addEventListener call.
You cannot attach an event to multiple elements at once. You need to loop over them.
Why do you have two different classes? i.e. 'wrongAnswer' and 'wrong-answer'? Please make sure that you stick with one convention.
I added an onReady() to wait for the DOM to load before accessing and adding listeners to the elements.
Addition Information
Below, I have wrapped the document.getElementsByClassName(className) call with [].slice.call(scope, [begin[, end]]) because the result of getElementsByClassName is a NodeList. You cannot treat a list like an array in JavaScript. Since I used Array.prototype.forEach to loop over the elements, they needed to transformed into an array. This is simply syntactic sugar in order to make the code look more aesthetically pleasing and readable.
This could have easily been accomplished with a for-loop:
var nodes = document.getElementsByClassName("rightAnswer");
for (var i = 0; i < nodes.length; i++) {
var el = nodes[i];
el.addEventListener('click', clickHandler);
}
Code
var wrongTextArr = ['Try Again!', 'Wrong!', 'Incorrect!'];
var guesses = 0;
onReady(function() {
// Set the number of guesses equal to the number of questions - 1.
guesses = document.querySelectorAll('.question button').length - 1;
[].slice.call(document.getElementsByClassName('wrongAnswer')).forEach(function(el) {
el.addEventListener('click', clickHandler);
});
[].slice.call(document.getElementsByClassName('rightAnswer')).forEach(function(el) {
el.addEventListener('click', clickHandler);
});
});
function clickHandler(e) {
var text = '';
var target = e.target;
var targetClass = target.className;
if (guesses < 1) {
text = 'You have reached the max number of attempts!';
} else if (targetClass === 'wrongAnswer') {
text = wrongTextArr[--guesses]; // Decrement guesses.
} else if (targetClass === 'rightAnswer') {
text = 'Correct!';
} else {
text = 'Unexpected Error!';
}
document.getElementById('answer').innerHTML = text;
}
function onReady(callback) {
var intervalID = window.setInterval(function() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 1000);
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
In the code above, I tried not to stray too far away from your original code, I just simply pointed out things that made your code not work and fix them with the minimalist amount of effort. Here is my solution that I would go with.
var wrongTextArr = ['Try Again!', 'Wrong!', 'Incorrect!'];
var guesses = 0;
onReady(function() {
// Set the number of guesses equal to the number of questions - 1.
guesses = document.querySelectorAll('.question button').length - 1;
addEventListeners('button[class$="Answer"]', 'click', function(e) {
document.getElementById('answer').innerHTML = getText(e.target.className.split());
});
});
function getText(classList) {
if (guesses < 1) {
return 'You have reached the max number of attempts!';
} else if (classList.indexOf('wrongAnswer') > -1) {
return wrongTextArr[--guesses]; // Decrement guesses.
} else if (classList.indexOf('rightAnswer') > -1) {
return 'Correct!';
} else {
return 'Unexpected Error!';
}
}
// Generic functions.
function addEventListeners(selector, event, listenerFn) {
[].slice.call(document.querySelectorAll(selector)).forEach(function(el) {
el.addEventListener(event, listenerFn);
});
}
function onReady(callback) {
var intervalID = window.setInterval(function() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 1000);
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>

Lots of good answers.. Here is another approach,
HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">2</button>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">5</button>
<button class="rightAnswer" type="button" onclick="checkAnswer(this)">6</button>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
JS:
<script>
var count = 0;
var wrongtext = ["Incorrect!", "Wrong!", "Try Again!"];
function checkAnswer(el) {
if (el.classList.contains('wrongAnswer')) {
count++;
if(count === 3)
count = 0;
alert(wrongtext[count])
}
if (el.classList.contains('rightAnswer')) {
alert('correct');
}
}
</script>
Demo:
https://jsfiddle.net/cubq361t/22/

I am not totally sure how to make it so it will say different things like "wrong" and "incorrect" but I hope this will point you in the right direction:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="section">
<p>How many sides does a hexagon have?</p>
<input type="button" onClick="wrongAnswer()" value="2">
<input type="button" onClick="wrongAnswer()" value="5">
<input type="button" onClick="rightAnswer()" value="6">
<input type="button" onClick="wrongAnswer()" value="10">
<p id="text"></p>
</div>
<script>
function wrongAnswer() {
document.getElementById('text').innerHTML = "Wrong";
}
function rightAnswer() {
document.getElementById('text').innerHTML = "Correct!";
}
</script>
</body>
</html>

Here is an updated version of your code. The main issue you had was mixing up your variable and function names.
Here is a
Fiddle
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
<script>
var text;
var wrongAnswers = document.getElementsByClassName("wrongAnswer");
var rightAnswers = document.getElementsByClassName("rightAnswer");
for (var i = 0; i < wrongAnswers.length; i++) {
// alert( wrongAnswers[i]);
wrongAnswers[i].addEventListener('click', printWrongAnswer);
}
for (var i = 0; i < rightAnswers.length; i++) {
rightAnswers[i].addEventListener('click', printRightAnswer);
}
function printRightAnswer() {
text = "Correct!";
printAnswer();
};
function printWrongAnswer() {
text = "Incorrect!";
text += "Wrong!";
text += "Try Again!";
printAnswer();
}
function printAnswer() {
document.getElementById("answer").innerHTML = text;
}
</script>

In addition to the answers of Mr. Polywhirl and Bellash:
If you are new to JavaScript you should try to understand how the EventBindings are working. Every binding in JavaScript is an event, so if you click somewhere the Browser will check if he will find a binding which is listening to the event "click". So its irrelevant when you bind the event but it has to be before the click. However you have to tell JavaScript which function he has to call if someone clicks your button! Thats because events are kinda "floating" in you browser scope, they are present but know one knows when they are actually be triggered but if they are getting triggered the script have to know what gets triggered or in other words: which functionality should be triggered now?
Your lines
var wrongAnswer = document.getElementsByClassName("wrongAnswer").addEventListener("click");
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click");
are wrong because you never told the event "click" what functionality should be executed if the button is clicked.
The call or one type of a correct call would be:
var someFunction = function() { // DO YOUR AWESOME WORK PLS! }
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click", someFunction);
and in addition to that:
I don't know how experienced you are in programming but this lines
text = "Incorrect!";
text = "Wrong!";
text = "Try Again!";
will override each other, because you are using the same variable in all 3 rows ;)
Mr. Polywhirl and Bellash posted you some good example to begin with. Try them out and try to understand them!
Hope this makes it a bit clearer!
cheers,
Sebastian

Here's a rewrite of your code, providing comments as a sort of tutorial:
Update: added random response generation.
HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<!--
Use a common class ('answer-button' used here) for all buttons
so that clicks can be easily handled with a single listener.
Since you know any answers that aren't right are wrong, you can
simply add a 'right-answer' class for that one and leave the
others as is.
-->
<button class="answer-button" type="button">2</button>
<button class="answer-button" type="button">5</button>
<button class="answer-button right-answer" type="button">6</button>
<button class="answer-button" type="button">10</button>
</div>
<div>
<!--
Using an id is often unnecessary, so I'd switch this to a class.
Since the above buttons represent answers, using an "answer" class
on this paragraph can bring confusion, so I'd recommend using something
more accurate, such as "response".
-->
<p class="response"></p>
</div>
<!--
Generally you'll want your js in a separate file. If you include the script, whether
inline or separate, at the bottom of the body element, as you did initially, it will
automatically execute after the dom has initialized, which is good.
-->
JavaScript:
// Wrap in an immediately invoking function expression
// to keep your variables off the global scope.
(function() {
// Capture all of your response phrases in an object.
var responses = {
correct: [
"Correct!"
],
incorrect: [
"Wrong!",
"Try Again!",
"Incorrect!"
]
};
// Get the element that will display your answer.
// getElementsByClassName returns an array, so get the
// first element in the array.
var response = document.getElementsByClassName('response')[0];
// Get all of the answer buttons.
var answerButtons = document.getElementsByClassName('answer-button');
// Set a listener on each answerButton element.
for (var i = 0; i < answerButtons.length; i++) {
// Add the event listener to the element. When the event occurs,
// the checkAnswer function will run, and will be passed an event object.
answerButtons[i].addEventListener('click', checkAnswer);
}
// event is an object that is automatically passed in
// when the listener calls this function, and event.target
// is the element where the event occurred.
function checkAnswer(event) {
// initialize a variable for the message
var message;
// get the element where the event occurred
var element = event.target;
// get all classes from target element
var classes = event.target.className;
// classes will be in a space-separated string, so
// we convert that to an array
classes = classes.split(' ');
// check if a specific class is in the array
if (classes.indexOf('right-answer') >= 0) {
// if the 'right-answer' class is there, they
// clicked the right answer.
message = getRandomArrayElement(responses.correct);
} else {
// otherwise, they clicked the wrong answer
message = getRandomArrayElement(responses.incorrect);
}
// set the target element's content to the message
response.textContent = message;
}
function getRandomArrayElement(array) {
// This function picks a random element from an array and
// returns it.
// You're going to want to pick one of these array items by their
// index, so we'll set up variables to capture the lowest and
// highest possible numbers that can be used.
var min = 0;
var max = array.length - 1;
// Javascript provides random numbers using the Math.random function,
// wich gives a random float between 0 and 1. The expression below
// uses that to generate a random number within a given range - in this
// case, between min and max.
var index = Math.floor(Math.random() * (max - min + 1)) + min;
return array[index];
}
})();

I have edited your code to help you understand how you could deal with .getElementsByClassName
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="rightAnswer" type="button">10</button>
</div>
<div>
<p id="answer">ok</p>
</div>
<script>
var text="...",
wrongs=document.getElementsByClassName("wrongAnswer"),
rights=document.getElementsByClassName("rightAnswer"),
wrongTexts=["Incorrect","Try Again","Wrong!"],
i=0;
for(var i=0; i< wrongs.length; i++){
wrongs[i].addEventListener("click",function(e){
text = "Incorrect!";
DisplayText();
});
}
for(var i=0; i< rights.length; i++){
rights[i].addEventListener("click",function(e){
text = "Correct!";
DisplayText();
});
}
function DisplayText(){
i=i%wrongTexts.length;
text=text=="Correct"?text:wrongTexts[i++];
document.getElementById("answer").innerHTML = text;
}
</script>

Make a function first and the assign it to the buttons like
<button onclick="myFunction()">Click me</button>
<p class="demo"></p>
Then in the JS
function myFunction() {
document.getElementByClassName("demo").innerHTML = "Hello World";
}
in your pen make a function add all the logic in it and call it on button click

Related

Javascript code to get several random elements from array not working

I've just started with JS, and I'm trying to get random elements from an array. The amount is decided by a user's input, and that part works, I think. The functions are called by onClick of buttons.
Scouring the internet has given me the solution below as the best one, but I can't make the part of fetching elements work even in console.log.
What I actually see in console is an empty array [] with length:0
What's the matter with my code? This is the way to do it I keep seeing on forums and people say it works for them and it's basically the same code with changed words.
userArray = [];
function addElement(){
let element = document.getElementById("add-input").value;
userArray.push(element);
document.getElementById("add-input").value = "";
}
function getElements(){
let amount = document.getElementById("amount-input").value;
newList = [];
for(i=0; i<amount.value; i++){
randomElement = userArray[Math.floor(Math.random() * userArray.length)];
newList.push(randomElement);
}
console.log(newList);
}
<div class="phase-add">
<p class="label-p">Input an element</p>
<div class="input-box">
<input class="add-input" type="text" name="add-input" id="add-input">
<button class="add-btn" onclick="addElement()">Add</button>
</div>
</div>
<div class="phase-get">
<div class="input-box">
<p class="label-p">Choose the amount</p>
<input type="text" name="amount-input" id="amount-input">
</div>
<button onclick="getElements()">Get elements</button>
</div>
The Variable amount is already a string/number. You need not get the value of it again in the for loop. Changing to for(i=0; i<amount; i++){ in for loop will fix the issue.
userArray = [];
function addElement(){
let element = document.getElementById("add-input").value;
userArray.push(element);
document.getElementById("add-input").value = "";
}
function getElements(){
let amount = document.getElementById("amount-input").value;
console.log(amount)
newList = [];
for(i=0; i<amount; i++){
randomElement = userArray[Math.floor(Math.random() * userArray.length)];
newList.push(randomElement);
}
console.log(newList);
}
<input id = "add-input" type = "text" ></input>
<button onclick = "addElement()">Add Element</button>
<input id = "amount-input" type = "number"></input>
<button onclick = "getElements()">Get Elements</button>

Compare a user inputted number with a randomly generated number in Javascript

I want to create a randomly generated number, ask the user to enter a number, then compare the two and then show a popup telling whether or not they match. This is my code
function myFunction() {
var num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === secondInput)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
<button onclick="myFunction()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="myFunction1()">Compare</button>
<p id="demo1"></p>
This code works. Please know that there were a couple of improvements:
You referenced to myFunction() before the javascript is loaded.
You need to keep the var num in global scope if you want to reference it in other places, without passing them as an argument.
When comparing values, make sure to select the right input field and to convert the value string to a Number.
var num;
function myFunction() {
num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
document.getElementById("button1").addEventListener('click', myFunction)
document.getElementById("button2").addEventListener('click', myFunction1)
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === +secondInput) {
window.alert("Same");
}
else {
window.alert("Don't do that again cvv");
}
}
<button id="button1" >press the button to see the code</button>
<p id="demo"></p>
code: <input id="demo1" type="text" name="code" required/><br/><br/>
<button id="button2">Compare</button>
<p></p>
First you have to define num in the global scope to be accessable by the two functions and you have to make the first function just show the number without generating a new number every time.
var num;
function show() {
document.getElementById("demo").innerHTML = num;
}
function randomizeAndCompare() {
num = Math.floor(1000 + Math.random() * 9000);
var secondInput = document.getElementById("demo1").value;
if( num === secondInput){
window.alert("Same");
}
else{
window.alert("Don't do that again cvv");
}
}
<button onclick="show()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="randomizeAndCompare()">Compare</button>
<p id="demo1"></p>
There are a couple of tings here.
First, myFunction1() isn't closed. You should also rename it to something more meaningful, like "compareValue()". That way it is easier to read the code.
You also aren't making a comparison of the two numbers in your compareValue()-function. Your 'num' variable isn't defined. You are also trying to extract the user input value from the button.
See my suggestion for changes:
function generateRandom() {
document.getElementById("demo").innerHTML = Math.floor(1000 +
Math.random() * 9000);
}
function compareValues() {
var num = document.getElementById("demo").innerHTML;
var input = document.getElementById("number").value;
if( num === input)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
}
HTML:
<button onclick="generateRandom()">press the button to see the code</button>
<p id="demo"></p>
code: <input id="number" type="text" name="code" required/><br/><br/>
<button onclick="compareValues()">Compare</button>
<p id="demo1"></p>

Changing Javascript variable value after onclick action

Pretty new to this Javascript thing.
I want to change a Javascript variable when a user inserts a number into an input field in my HTML document and clicks a button.
I'm assuming you'd use a function, but how do you gather the data and change the variable?
The stuff I tried to make looks a little something like this.
HTML
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value;
}
but it's not working!
Edit 1:
Wow. I didn't think I'd get this kind of attention. I also found it a bit strange it didn't work at first.
The question I'm asking is partly for a calculator here: https://titomagic.com/debug
It's simple, you type in a number, click the button and it calculates (based on other variables) to a result on the bottom.
Here's a link to the Javascript file, if you wanna have a look: https://titomagic.com/js/bursdagskalkulator.js
To those of you asking; yes, I've been testing with a console.log and the variable is not changing. It's not affecting the other variables (as it should?).
Also I've never heard of JSfiddle.
I discovered few things in the summarizeGjester() function. First of all I moved all the Javascript code in the bursdagskalkulator.js file inside the summarizeGjester() function. Also I converted var antallGjester to integer using parseInt() function, because it was treated as string before.
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester); //integer conversion
Also the first Boolean comparison was changed to
if ((antallGjester < 10) && (antallGjester > 0)), so that the second one would work if there’s 0 value: else if (antallGjester === 0).
function summarizeGjester() {
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester);
var fastPris = 1500;
var fastPrisDifferanse = 10;
var gjestePris = 120;
var gjesteDifferanse = antallGjester - fastPrisDifferanse;
var gjesteSum = gjestePris * gjesteDifferanse;
var gjesterTotalt = 0;
if ((antallGjester < 10) && (antallGjester > 0)) {
console.log("antallGjester < 10");
gjesterTotalt = 1500;
} else if (antallGjester === 0) {
console.log("antallGjester === 0");
gjesterTotalt = 0;
} else {
console.log("else");
gjesterTotalt = fastPris + gjesteSum;
}
document.querySelector('#results').innerHTML = gjesterTotalt;
}
<form>
<div class="form-group">
<label for="gjesterAntall">Antall barn:</label>
<input type="number" class="form-control" id="gjesterAntallInput">
</div>
<button class="btn btn-lg btn-warning" onclick="summarizeGjester()" type="button" id="sumGjester">Legg sammen</button>
</form>
<h1 class="text-center" style="font-size:80px;"><strong><span id="results">0</span>,-</h1>
I hope this helps :-)
HTML
<input type="number" id="inputField" ClientIDMode="static">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById('inputField').value;
alert(a);
}
Use Static ClientIDMode for stable id and access after page rendering
PlaceHolders canh change childe's id
I suppose this will work for you
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value || a;
document.getElementById("result").innerText = parseFloat(a);
}
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe">Click me</button>
<div>Result: <span id="result"></span></div>
Edited:
The reason behind this code is not running in jsfiddle is here.
After making the changeTheVariable() global variable this code will work in jsfiddle also. Here https://jsfiddle.net/1b9cfmje/
Use the following javascript code:
window.onload = function(){ var a = 0; window.changeTheVariable = function() { a = document.getElementById("inputField").value || a; document.getElementById("result").innerText = parseFloat(a); }}

Using localStorage to Remember if User Already Voted

I'm trying to use localStorage to remember if the user has already voted. I have 5 buttons — all with a unique ID to help me keep track of things.
When a user clicks on one of these buttons (e.g., button-1), I store the ID of that button with a value. So in localStorage, it looks something like this: key: button-1, value: clicked.
If the user has already clicked (voted) on that button, it needs to display a message, something like "Thank you for your vote." Otherwise it should keep that button active.
I'm struggling to do this systematically if I have multiple buttons. Do I store a separate key for each button in localStorage? Do I append them under one key? I am not sure.
My JSFiddle is here as an example with 3 buttons http://jsfiddle.net/d8kt69rp
HTML
<div id="button-1">
<button value="yes" onclick="recordFeedback(1, this);">Button 1</button>
</div>
<div id="button-2">
<button value="yes" onclick="recordFeedback(2, this);">Button 2</button>
</div>
<div id="button-3">
<button value="yes" onclick="recordFeedback(3, this);">Button 3</button>
</div>
JS
// If user has already voted, just display them a 'thanks' message
if (localStorage.getItem('button-1')) {
var div = document.getElementById('button-1');
div.innerHTML = 'Thank for your feedback';
}
// Record user feedback based on the button they clicked
function recordFeedback(id, response) {
userResponse = response.value;
var div = document.getElementById('button-' + id);
if (userResponse === 'yes') {
div.innerHTML = 'Thanks for your feedback.';
console.log('button-' + id + ' was clicked.');
localStorage.setItem('button-' +id, 'clicked');
}
}
You can do something like this:
Fiddle: http://jsfiddle.net/AtheistP3ace/d8kt69rp/2/
HTML (added class to divs):
<div class="button-div" id="button-1">
<button value="yes" onclick="recordFeedback(1, this);">Button 1</button>
</div>
<div class="button-div" id="button-2">
<button value="yes" onclick="recordFeedback(2, this);">Button 2</button>
</div>
<div class="button-div" id="button-3">
<button value="yes" onclick="recordFeedback(3, this);">Button 3</button>
</div>
JS:
// Wait for DOM to be ready
document.addEventListener('DOMContentLoaded',
function() {
document.removeEventListener('DOMContentLoaded', arguments.callee, false);
// Get all the button divs
var buttons = document.getElementsByClassName('button-div');
var index = 0, length = buttons.length;
for (; index < length; index++) {
// For each one check if it has a localStorage value
if (localStorage.getItem(buttons[index].id) == 'clicked') {
buttons[index].innerHTML = 'Thank for your feedback';
}
}
}, false
);
As for having a key for each or keeping them all together. That's personal preference. Me, I would prefer keeping them together. Feels cleaner although a little more code.
Fiddle: http://jsfiddle.net/AtheistP3ace/d8kt69rp/4/
function recordFeedback(id, response) {
userResponse = response.value;
var div = document.getElementById('button-' + id);
if (userResponse === 'yes') {
div.innerHTML = 'Thanks for your feedback.';
// Get storage and parse it to an object
var storage = JSON.parse(localStorage.getItem('userResponses'));
// If storage doesn't exist initialize it
if (!storage) storage = {};
storage['button-' + id] = 'clicked';
// Make it a string and set it
localStorage.setItem('userResponses', JSON.stringify(storage));
}
}
document.addEventListener('DOMContentLoaded',
function() {
document.removeEventListener('DOMContentLoaded', arguments.callee, false);
var storage = JSON.parse(localStorage.getItem('userResponses'));
// Don't waste time finding or looping if no votes
if (storage) {
var buttons = document.getElementsByClassName('button-div');
var index = 0, length = buttons.length;
for (; index < length; index++) {
if (storage[buttons[index].id] == 'clicked') {
buttons[index].innerHTML = 'Thank for your feedback';
}
}
}
}, false
);

Javascript time out div

I have an alert that says you're right/wrong. I want to put a div that will appear for a few seconds instead of the alert. So when the right/wrong answer is chosen this div will appear instead of the alert. I know a timeout function would be needed but I cant seem to get it to work. I've tried a few times and nothing is working for me. Does anyone know how I would go about this?
This is the html (divs)
<div id = "your wrong">
wrong answer!
</div>
<div id = "right answer">
Right answer!
</div>
This is the javascript for the alert
function characterclicked(nr) {
if (nr == oddoneout[currentQuestionIndex].answer) {
alert("You're right!");
score+= 200;;
}
else{
alert("you are wrong it was " + oddoneout[currentQuestionIndex].characterName);
}
nextQuestion();
}
Just about the only thing you're not allowed to use in an id value in HTML is a space. :-) So we'll need to change those ids.
But then it's a simple matter of having them start off invisible (display: none), showing the relevant one (display: block), and then hiding it again after a delay via setTimeout.
document.getElementById("btnRight").onclick = function() {
show("right");
};
document.getElementById("btnWrong").onclick = function() {
show("wrong");
};
function show(id) {
var element = document.getElementById(id);
element.style.display = "block";
setTimeout(function() {
element.style.display = "none";
}, 1000); // 1000ms = 1 second
}
<div id="wrong" style="display: none">
wrong answer!
</div>
<div id="right" style="display: none">
Right answer!
</div>
<div>
<input type="button" id="btnRight" value="Show Right">
<input type="button" id="btnWrong" value="Show Wrong">
</div>
I will hope help you
var score = 0;
var oddoneout = Array();
oddoneout[0] = {answer: "2"};
var currentQuestionIndex = 0;
var btnReply = document.getElementById("reply");
btnReply.onclick = function(){
var answer = document.getElementById("answer").value;
characterclicked(answer);
};
function characterclicked(nr) {
var feedback = document.getElementById("right_answer");
if (nr == oddoneout[currentQuestionIndex].answer) {
score+= 200;
}else{
//alert("you are wrong it was " + oddoneout[currentQuestionIndex].characterName);
feedback = document.getElementById("your_wrong");
}
feedback.style.display = "block";
setTimeout(function(){
feedback.style.display = "none";
}, 2000);
//nextQuestion();
}
.feedback {
display: none;
color: red
}
<div class="question">
how many is 1 + 1 ?
</div>
<input type="text" id="answer" />
<input type="button" id="reply" value="reply" />
<div id = "your_wrong" class="feedback">
wrong answer!
</div>
<div id = "right_answer" class="feedback">
Right answer!
</div>
First thing you should do is to make the element that will contain the message invisible. You can do this by using display: none, either in the element's style attribute or in a CSS style sheet (preferred).
Next, we'll craft a function that shows the message. Since it can show either one of two messages, it will take an argument, so it knows whether to show "right" or "wrong".
function showMessage(right) { ... }
The right argument can be a boolean to keep it simple. From here, we can use only a single <div> and change it's text according to whether or not right is true.
Let's give it an id of message (you were using spaces in your IDs, which you cannot do).
function showMessage(right) {
var text = "You are ";
text += right? "right" : "wrong";
// Let's get the result <div>
var messageDiv = document.getElementById("message");
// and change it's text
messageDiv.innerText = text;
}
Now, all that's left is to show the message <div>, and after a few seconds make it disappear again. Let's use 5 seconds for this example. 5 seconds are 5000 milliseconds, which is what the timeout functions use as a unit.
function showMessage(right) {
var text = "You are ";
text += right? "right" : "wrong";
// Let's get the result <div>
var messageDiv = document.getElementById("message");
// and change it's text
messageDiv.innerText = text;
// and show it, and hide it after 5 seconds
messageDiv.style.display = "block";
setTimeout(function(){
messageDiv.style.display = "none";
}, 5000);
}
And that's it! If you call the function with true as an argument, it will show you "You are right". Otherwise, it will show you "You are wrong".
Here's a Jsfiddle for you to see it working.
Edit
If you also want to show the correct answer when the user is wrong, you can do so with a second argument:
function showMessage(right, answer) {
var text = "You are ";
text += right? "right!" : "wrong. The answer was " + answer;
...
}

Categories