Trying to get the button called, "check" to show the var result from the answer prompt1 function. For whatever reason when I run the code nothing happens when the button is clicked. I know the calculation is right because, when I set the answer button to give the intended alert, it works properly. How do I get the second button to display my results entered?
<!DOCTYPE html>
<head>
<!--
Name: Dakota Trumbull
Date:
Class:
Purpose:
-->
<title>Math Test</title>
</head>
<body>
<h1>Simple Math Test</h1>
<p>Q1: 5 + 9 = ??</p>
<button id = "Q1A" onclick = "answerPrompt1()">Answer</button>
<button id = "Q1C" onclick ="showResult()">Check</button>
<p></p>
<p>Q2: 4 * 6 = ??</p>
<button id = "Q2A">Answer</button>
<button id = "Q2C">Check</button>
<p></p>
<p>Q3: 25 - 14 = ??</p>
<button id = "Q3A">Answer</button>
<button id = "Q3C">Check</button>
<p></p>
<p>Q4: 48 / 3 = ??</p>
<button id = "Q4A">Answer</button>
<button id = "Q4C">Check</button>
<p></p>
<p>Q5: 26 % 6 = ??</p>
<button id = "Q5A">Answer</button>
<button id = "Q5C">Check</button>
</body>
<script>
//Q1
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: ");
var convertedNum1 = parseInt(answer1, 10);
var result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}
</script>
</html>
result is declared in answerPrompt1, which gives it local scope (i.e. it isn't visible outside that function). move the declaration to just before the function:
var result = "You have not given an answer yet";
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: ");
var convertedNum1 = parseInt(answer1, 10);
result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}
<body>
<h1>Simple Math Test</h1>
<p>Q1: 5 + 9 = ??</p>
<button id = "Q1A" onclick = "answerPrompt1()">Answer</button>
<button id = "Q1C" onclick ="showResult()">Check</button>
</p>
</body>
You should change your result variable in a way that it can be accessible to both functions answerPrompt1() and showResult() You can have a clear understanding about how javascript scope works from here.
var result = "You have not given an answer yet"; //this variable is accessible to both functions
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: "); //this variable only accessible inside the function answerPrompt1()
var convertedNum1 = parseInt(answer1, 10);
result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}
Related
<html>
<head>
<script defer>
let start;
let num = 0;
let btn = document.getElementById('btn1');
btn.onclick = timer;
function timer() {
if (start === undefined) {
start = setInterval(count, 1000);
}
}
clearInterval(start)
function count () {
let input = document.getElementById('input1').value;
let currentLet = input.charAt(num);
if (currentLet !== '')
document.getElementById('output1').innerHTML = 'Your letters are: ' + currentLet;
else {
document.getElementById('output1').innerHTML = 'Your letters are: done'
}
num++;
}
</script>
</head>
<body>
<h2>Programming Question 1</h2>
<input type="text" id="input1"><button id="btn1">Press to start</button>
<p id="output1"></p>
</body>
</html>
I am trying to create a program where you enter text into the text box and then, when you click a button, it will show one letter per second until all the letters have been outputed. However, I need the setInterval function to terminate after the output says "done". How do I do that? I know clearInterval is used, but I can't figure out how to execute it automatically after it reaches 'done'. I created 'start' in order to make sure the interval function doesn't execute multiple times if you click on the button more than once before it finishes reading out all the letters of the current input. I also want the interval to start counting again if I press the button again or enter a new input value
Your first problem is in the num variable, you must reset the num variable of every click of the button.
function timer() {
if () {
num = 0
}
}
You can use clearInterval after the done log
if (currentLet !== '')
document.getElementById('output1').innerHTML = 'Your letters are: ' + currentLet;
else {
document.getElementById('output1').innerHTML = 'Your letters are: done'
clearInterval(start)
}
And last, you can't control the interval with undefined because you are declaring an interval the first time and it will never undefined. You must use another variable like flag
Full code;
let start;
let num = 0;
let flag;
let btn = document.getElementById('btn1');
btn.onclick = timer;
function timer() {
if (!flag) {
flag = true;
start = setInterval(count, 1000);
num = 0
}
}
function count() {
let input = document.getElementById('input1').value;
let currentLet = input.charAt(num);
if (currentLet !== '')
document.getElementById('output1').innerHTML = 'Your letters are: ' + currentLet;
else {
document.getElementById('output1').innerHTML = 'Your letters are: done'
clearInterval(start)
flag = false
}
num++;
}
<html>
<head>
</head>
<body>
<h2>Programming Question 1</h2>
<input type="text" id="input1"><button id="btn1">Press to start</button>
<p id="output1"></p>
</body>
</html>
My aim is to use a single input to collect numbers and strings then use it to determine a math operation.
For example, I parse in values such as √64 intending to find the square root of 64. Knowing that this is no valid javascript, so I decided to get the first character with result[0]; which is "√" and then slice out the remaining values with result.slice(1); which is "64", then when the condition that result[0] == "√" is true then Math.sqrt(sliceVal) . This seems perfect and runs well in a mobile editor, but doesn't run in any web browser.
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
I do not know why It is not running at your end but It is working perfectly according to your requirement I tested above code :)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function actn() {
var input = document.getElementById("test").value;
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
alert(Math.sqrt(sliceVal));
}
alert("No match found");
}
</script>
</head>
<body>
<input type="text" id="test" />
<button type="button" onclick="actn()">Test</button>
</body>
</html>
Checking ASCII value instead of character comparison should work.
<html>
<body>
<input type="text" id="input" />
<button type="button" id="sqrRoot">Square Root</button>
<h1 id="display"></h1>
<script>
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
/* Ascii value for √ is 8730 */
if (firstVal.charCodeAt(0) === 8730) {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
document.getElementById("sqrRoot").addEventListener("click", function () {
actn();
});
</script>
</body>
</html>
I'm currently working on a piece of coursework for Computer Science where we need to automate a traffic light sequence using buttons e.g "Traffic Lights On" or "Traffic Lights off". When I run my program through the internet explorer debugger, I get the error code: "The value of the property 'Timer' is null or undefined, not a Function object" on line 5 of my coding even though I've defined it as a function later on in the script. My programming can be found below:
<!DOCTYPE html>
<html>
<body>
<p>
<button type="button" onclick="Timer()"> Start Lights</button>
<button type="button" onclick="StopTimer()"> Stop lights</button>
</p>
<img id = "TrafficLight" src="http://imgur.com/FHT9OoG.jpg">
<script>
var TrafficLightList = [
"http://imgur.com/FHT9OoG.jpg",
"http://imgur.com/XZ1PxGh.jpg",
"http://imgur.com/5DUX0Wy.jpg",
"http://imgur.com/WpeEMZU.jpg"
];
var Automation = 0;
var TimeBetweenChange = null;
function ChangeLightAutomated() {
if(Automation == TrafficLightList.length) Automation = 0;
var Light = document.getElementById("TrafficLight");
image.src = TrafficLightList[Automation];
image.alt = TrafficLightList[Automation] //debugger
Automation = Automation + 1;
}
function Timer() {
if(!TimeBetweenChange) {
TimeBetweenChange = self.setTimeBetweenChange(ChangeLightAutomated, 1000);
}
}
function StopTimer() {
self.clearTimeBetweenChange(TimeBetweenChange);
TimeBetweenChange = null;
}
</body>
</script>
</html>
As I've said before, the error appears to be on line 5 of the program as "Timer" is not defined even though I define what Timer's function is on line 28.
There are several undefined variables in your code, for example you do var Light = document.getElementById("TrafficLight"); and then image.src = TrafficLightList[Automation]; in which case image is undefined. Also, there's no self defined anywhere.
Here's a working example of what you wanted to do:
var timer = (function () {
var trafficLightList = [
"http://imgur.com/FHT9OoG.jpg",
"http://imgur.com/XZ1PxGh.jpg",
"http://imgur.com/5DUX0Wy.jpg",
"http://imgur.com/WpeEMZU.jpg"
];
var automation = 0;
var interval = null;
function changeLightAutomated() {
if(automation == trafficLightList.length) automation = 0;
var image = document.getElementById("TrafficLight");
image.src = trafficLightList[automation];
image.alt = trafficLightList[automation] //debugger
++automation;
}
function startTimer() {
interval = setInterval(changeLightAutomated, 1000);
}
function stopTimer() {
clearInterval(interval)
}
return {
start: startTimer,
stop: stopTimer
}
})()
document.getElementById('start').addEventListener('click', function() {timer.start()})
document.getElementById('stop').addEventListener('click', function() {timer.stop()})
<!DOCTYPE html>
<html>
<body>
<p>
<button type="button" id="start"> Start Lights</button>
<button type="button" id="stop"> Stop lights</button>
</p>
<img id = "TrafficLight" src="http://imgur.com/FHT9OoG.jpg">
<script>
</script>
</body>
</html>
Add ID's to the buttons:
<input type="button" id="button1_id" value="Some description" onclick="Timer()">
<input type="button" id="button1_id" value="Some description" onclick="StopTimer()">
I added a value too, so the button has text inside. Change 'Some description' to some suggestive text
And then, for each one do (on javascript):
var timerSelector = document.getElementById("button1_id");
timerSelector.onclick = Timer;
var stopTimerSelector = document.getElementById("button2_id");
stopTimerSelector.onclick = StopTimer;
or simply:
document.getElementById("button1_id").onclick= Timer;
document.getElementById("button2_id").onclick = StopTimer;
Add these lines to the javascript.
Let me know if it solved the problem.
So I have a scoreboard for a game I am making, if you press a button you get one point, this is the scoreboard. But I want to have it so that if you reach 10 points, you are taken to an other html, a victory screen.
This is my JS + HTML
<script type="text/javascript">
var clicks1 = 0;
function updateClickCount1(){
document.getElementById("clickCount1").innerHTML = clicks1;
}
</script>
<button type="button" onclick='clicks1++;updateClickCount1()' id="push"> Score +1 </button>
<div id="clickCount1">0</div>
</div>
Check the value within the function and redirect if it reached 10.
<script type="text/javascript">
var clicks1 = 0;
function updateClickCount1(){
document.getElementById("clickCount1").innerHTML = clicks1;
if(clicks1 == 10)
window.location = 'newpahe.html';
}
</script>
<script>
var clicks1 = 0;
function updateClickCount1(){
document.getElementById("clickCount1").innerHTML = ++clicks1;
if(clicks1>9) window.location.href="victory.html";
}
</script>
you can do like this set your counter as 0, increment it after user reach the score greater than 9 redirect to the victory page
Inside your update function, check if the number of clicks is greater or equal than 10. if it is the case use window.location to redirect
var clicks1 = 0;
function updateClickCount1() {
document.getElementById("clickCount1").innerHTML = ++clicks1;
if(clicks1 >= 10)
window.location = "victory.html";
}
<button type="button" onclick='updateClickCount1()' id="push">Score +1</button>
<div id="clickCount1">0</div>
I am making a puzzle website where you select a puzzle, I was wondering if there was a way of, instead of it being in pop up boxes it would be printed to the website. I don't mind what code we are using as I am fluent in most,
This is the code I have so far:
<body>
<script type="text/javascript">
function myFunction()
{
function ask() {
var a = (Math.round(Math.random()*1000000))
alert (a)
return prompt("What was the number?") == eval( a );
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction()">Remember the number</button>
</body>
<body>
<script type="text/javascript">
function myFunction2(){
function ask() {
var a = Math.floor(Math.random() * 10) + 1;
var b = Math.floor(Math.random() * 10) + 1;
var op = ["*", "+", "/", "-"][Math.floor(Math.random()*4)];
return prompt("How much is " + a + " " + op + " " + b + "?") == eval( a + op + b);
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction2()">Quick math</button>
</body>
</html>
</html>
So I was wondering if there was a way to make it show up as text and have a text box on the page to type into that would still work. And the design is able to be changed, so I can make a larger text box, or a larger font so it's not just an un-editable onclick.
All help greatly appreciated.
Thanks.
I did what I thought that you wanted to the "Remember the number" button click.
Sorry, had no time to do the other one.
HTML:
<body>
<button id="rmbrBtn">Remember the number</button>
</body>
<body>
<button id="quivkBtn">Quick math</button>
<div id="question_area">
</div>
</body>
</html>
</html>
JS & jQuery code:
$("#rmbrBtn").click(function()
{
// Answers collection
var questions = [];
// Check the correctness of the answer
function checkAnswer (){
total = questions.length,
correct = questions.filter(Boolean).length;
if(total < 5)
{
ask();
}else{
var answer = '<div>You got '+correct+'/'+total+' correct <input type="button" value="Ok" id="ansOk"/></div>';
$("#question_area").append(answer);
$("#ansOk").click(function(){
$(this).parent().empty();
$(this).parent().remove();
});
}
}
// Get the question
function ask() {
var a = (Math.round(Math.random()*1000000));
// View the generated number
var viewNumber = '<div>'+a+'<input type="button" id="ok" value="OK"/>'+'</div>';
// Prompt user with a text box
var promptVal = '<div>Enter your value: <input type="text" id="ans" /> <input type="button" id="prmtOk" value="Ok"/></div>';
// Append
$("#question_area").append(viewNumber);
$("#ok").click(function(){
$(this).parent().empty();
$(this).parent().remove();
$("#question_area").append(promptVal);
$("#prmtOk").click(function(){
var prmt = $("#ans").val();
var addVal = prmt == a;
questions.push(addVal);
checkAnswer();
$(this).parent().empty();
$(this).parent().remove();
});
});
}
// Run the function.
checkAnswer();
});
Online solution:
JSFiddle
Try to do the other one same as this.
Sorry had no time to comment also.
I think you can figure this out.
Just add a div at the top of your page and use jqueries .html() and you will be done
like
$('.header').html('You are correct.');
here is a fiddle http://jsfiddle.net/AMISingh/8nWKD/3/
This can also be done without JQuery and just JavaScript.
http://jsfiddle.net/8nWKD/4/
<div id="header" class="header">This is the header</div>
<div class="button" onClick="test_click()"> Click me!</div>
and the JavaScript
function test_click()
{
document.getElementById("header").innerHTML = "CORRECT!";
}