Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm very new to JavaScript and am attempting to make a simple maths game.
I'm holding the correct answer to my randomly generated maths questions in a variable named correctAnswer. I would like the value of this variable to be displayed in a button - so that when the user clicks it, they see a "Well done!" message.
This is what I've got so far - just the code to create my random questions:
var firstNumber;
var secondNumber;
var correctAnswer;
var userAnswer;
function additionQuestion() {
firstNumber = Math.floor(Math.random() * 10) + 11
secondNumber = Math.floor(1 + Math.random() * 9);
document.getElementById("additionQuestion").innerHTML = + firstNumber + " + " + secondNumber + " = ";
correctAnswer = (firstNumber + secondNumber);
}
Would anyone be able to help me with this?
Thanks in advance.
You can display value in a button, by accessing its value property.
For example you have a button like this
<input type="button" id="correct" />
you can display value in it like this:
document.getElementById("correct").value = correctAnswer;
use this line of code to change your button display text:
document.getElementById("yourButtonID").innerHTML= correctAnswer;
check this for more info: http://www.w3schools.com/jsref/prop_html_innerhtml.asp
use jquery;
var yourVariable = 48;
$(document).ready(function(){
$('.your-button').data('answer', 48);
$('body').on('click', '.your-button', function(e){
if($(this).data('answer') === yourVariable){
alert('good answer');
}else{
alert('try again');
}
});
});
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
When I click on this button the button disappears. im trying to make it so the button sticks on the screen and always adds one to the money variable. (sorry for the unclear explanation)
<!DOCTYPE html>
<html>
<body>
<script>
var money = 0;
function addMoney() {
money += 1;
document.write("Money: <b>" + money + "</b>");
}
</script>
<button type="button" onclick="addMoney()">Get a money</button>
</body>
</html>
I did not understand exacly what you want to do. But if you want to print the money variable on an element as you click the button, you can try:
<script>
var money = 0;
function addMoney() {
money += 1;
//document.write("Money: <b>" + money + "</b>");
document.getElementById('money-div').innerHTML = money;
}
</script>
<button type="button" onclick="addMoney()">Get a money</button>
<div id="money-div"></div>
You are overwriting document so you won't see your button after clicking. You do the rewriting this way:
document.write("Money: <b>" + money + "</b>");
Create an additional container for entering values into this content:
<div class="count">Money: <b>0</b></div>
And declare this content as a selector and then assign the value on click:
document.querySelector(".count b").textContent = money;
var money = 0;
function addMoney() {
money += 1;
document.querySelector(".count b").textContent = money;
}
<button type="button" onclick="addMoney()">Get a money</button>
<div class="count">Money: <b>0</b></div>
So I had this working last night, its a 10 questions quiz. I did a few revisions today, and now when I click to check the answer, I've lost the functionality that would display in the jumbotron if the answer was correct or not. The continue to next question still deletes and repopulates the list. Just the button to check the question answer is broken. Here's the jsFiddle link:
https://goo.gl/1cfgBO
The issue has to do with your i value not being valid in the listener callback block. You can resolve this by using your currentQuestion value instead, like so:
$('#submit').on('click', function() {
var answer = $('input[name="1"]:checked').val();
if (answer == questionsArray[currentQuestion]['answer']) {
correctAnswers++;
$('.jumbotron').html(answer + "?<br><br> That's correct! You have " + correctAnswers + " out of 10 correct!");
} else {
$('.jumbotron').html(answer + "? <br><br> Oh dear, that's so so wrong! You have " + correctAnswers + " out of 10 correct");
}
return false;
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am trying to localStore the history but it does not work. I tried JSON.stringify and a script called JStorage but I couldn't get either to work.
function updateHistory(video) {
getHistory();
blacklist[video["id"]] = true;
myhistory.push(video);
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
saveHistory();
}
function saveHistory() {
localStorage.setItem(myhistory, myhistory.innerHTML);
}
(The alert does show up)
function getHistory() {
localStorage.getItem(myhistory);
alert("working");
}
The point is, instead of storing the html part you better store the video object instead, you can store videos based on their id, and instead of array use javascript object:
function setVideo(video) {
var videos = JSON.parse(localStorage.getItem("myhistory") || "{}");
videos[video["id"]]=video;
localStorage.setItem("myhistory", JSON.stringify(videos));
}
function getVideos() {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return {};
else return JSON.parse(myhistory);
}
function getVideo(id) {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return null;
var videos = JSON.parse(myhistory);
return videos[id] || null;
}
now you can use getVideo to retrieve the video object by id.you can separate the part which shows the video, like:
function showVideo(video) {
blacklist[video["id"]] = true;
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
}
let's say you want to show the whole videos in the history:
var videos = getVideos();
for(var id in videos){
showVideo(videos[id]);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have the following javascript code for a rotating image. Those images are in a separate folder from the javascript. I want to link the rotation itself to another page. All images will go to the same link. The current code works great but I just don't know where I add the a href code or its syntax.
// JavaScript Document
//
// Type the number of images you are rotating.
NumberOfImagesToRotate = 3;
FirstPart = '<img src="domain/rotatingimages';
LastPart = '.gif" height="250" width="388">';
function printImage() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
document.write(FirstPart + r + LastPart);
}
Try this format
<img src='image_src' border="0"/>
It is up to you if you want to define the target attribute in <a> tag.
// JavaScript Document
//
// Type the number of images you are rotating.
var numberOfImagesToRotate = 3;
// Edit the destination URl here
var linkUrl = 'example.html';
// HTML-partials
var imgFirstPart = '<img src="domain/rotatingimages';
var imgLastPart = '.gif" height="250" width="388" border="0">';
var anchorFirstPart = '<a href="';
var anchorSecondPart = '">';
var anchorLastPart = '</a>';
function printImage() {
var r = Math.ceil(Math.random() * numberOfImagesToRotate);
document.write(anchorFirstPart + linkUrl + anchorSecondPart + imgFirstPart + r + imgLastPart + anchorLastPart);
}
I've been trying to figure this out for a while, and I'm totally stumped.
I'm writing a program that is supposed to display a basic series of multiple-choice questions. You see a question, you click one of the answers, and you move on to the next question.
The problem is, I can't figure out how to display one question, then display the next question when the user clicks one of the buttons. Nothing happens when I click a button. What's going wrong?
// progress meter
var progress = new Array();
for (var i = 0; i < questions.length; i++) progress.push("0");
var i = 0;
display(0);
// display questions
function display(i) {
var prg_string;
for (var j = 0; j < progress.length; j++) prg_string += progress[j];
document.write(
"<div id = 'background'>"
+ "<div id = 'progress'>" + progress + "</div>"
+ "<div id = 'title'>-JogNog Test v1-<br></br>" + tower + "</div>"
+ "<div id = 'question'>" + questions[i].text + "</div>"
+ "<div id = 'stats'>Level " + level + "/" + total_levels + " Question " + (i + 1) + "/" + questions.length + "</div>"
+ "</div>"
);
document.write("<button id = 'answer1' onclick = 'next(questions[i].answers[0].correct)'>" + questions[i].answers[0].text + "</button>");
if (questions[i].answers.length > 0)
document.write("<button id = 'answer2' onclick = 'next(questions[i].answers[1].correct)'>" + questions[i].answers[1].text + "</button>");
if (questions[i].answers.length > 1)
document.write("<button id = 'answer3' onclick = 'next(questions[i].answers[2].correct)'>" + questions[i].answers[2].text + "</button>");
if (questions[i].answers.length > 2)
document.write("<button id = 'answer4' onclick = 'next(questions[i].answers[3].correct)'>" + questions[i].answers[3].text + "</button>");
}
// go to next question, marking whether answer was right or wrong
function next(correct) {
if(correct) progress[i] = "T";
else progress[i] = "F";
i += 1;
display(i);
}
I haven't read through your code, (you might want to work on posting SSCCEs by focusing just on the part that handles the loop) but I get the feeling a loop is not what you want here. Loops are great if you need to automatically iterate through something. But really, you want to display only a single question at a time.
The easiest way to do this, assuming you have a means of handling each question independently, is just to keep track of which question the user is up to. Display that question. When the user submits an answer, call whatever function renders a question using the counter, plus one. Make sure to check that you haven't hit the end of the quiz so that you don't reference a question that doesn't exist.
Here's some pseudocode:
var questionNumber, questions; //assume these already have values
function printQuestion(questionNumber){ ... }
function nextQuestion(){
if(questionNumber < questions){
questionNumber++;
printQuestion(questionNumber);
}
else{
showResults();
}
}
I agree with #ngmiceli that a loop isn't what you want here. You want to display one question, and then create click event handlers that will move on to the next question when the user selects an answer to the previous question.
I went ahead and created a different setup to demonstrate. You can see a demo here:
-- jsFiddle DEMO --
But I'll walk through the process. First, I set up a basic HTML document:
<body>
<h1>-Test v1-</h1>
<h2>Simple Math</h2>
<div id="container">
<div><span id="numRight">0</span> of <span id="numQuestions">0</span></div>
<div id="question"></div>
<div id="answers"></div>
</div>
</body>
Then, I created a questions array, each element in the array being an object. Each question object contains the question itself, an array of possible answers, and an "answerIdx" property that indicates the array index of the correct answer.
questions = [
{
question: 'What is 0 / 6 ?',
options: ['0','1','2'],
answerIdx: 0
},
{
question: 'What is 2 + 2 ?',
options: ['72','4','3.5'],
answerIdx: 1
}
]
I also created some other variables that point to the HTML elements I am going to want to manipulate:
numRight = 0,
numQuestions = 0,
answerDiv = document.getElementById('answers'),
questionDiv = document.getElementById('question'),
numRightSpan = document.getElementById('numRight'),
numQuestionsSpan = document.getElementById('numQuestions');
Next, I created a 'displayQuestion' function which takes a single question object as a parameter:
function displayQuestion(q) {
// insert the question text into the appropriate HTML element
questionDiv.innerHTML = q.question;
// remove any pre-existing answer buttons
answerDiv.innerHTML = '';
// for each option in the 'options' array, create a button
// attach an 'onclick' event handler that will update
// the question counts and display the next question in the array
for(i = 0; i < q.options.length; i++) {
btn = document.createElement('button');
btn.innerHTML = q.options[i];
btn.setAttribute('id',i);
// event handler for each answer button
btn.onclick = function() {
var id = parseInt(this.getAttribute('id'),10);
numQuestionsSpan.innerHTML = ++numQuestions;
// if this is the right answer, increment numRight
if(id === q.answerIdx) {
numRightSpan.innerHTML = ++numRight;
}
// if there is another question to be asked, run the function again
// otherwise, complete the test however you see fit
if(questions.length) {
displayQuestion(questions.shift());
} else {
alert('Done! You got '+numRight+' of '+numQuestions+' right!');
}
}
answerDiv.appendChild(btn);
}
}
Finally, I displayed the first question:
displayQuestion(questions.shift());