How to change if statement from alert to text - javascript

How would I instead of have the if statement come up as an alert, have it appear as text on my page. Thanks
document.getElementById("button").onclick=function() {
if (document.getElementById("ask").value=="how tall are the pyramids") {
alert ("146.5 meters");
} else if (document.getElementById("ask").value == "how tall is the gateway arch") {
alert("630 feet");
} else if (document.getElementById("ask").value == "how tall is the empire state building") {
alert("6900 feet");

I may have misunderstood, but it sounds like you want to display the value in an html element rather than alerting the value. See the below example
document.getElementById("button").onclick = function() {
var val = document.getElementById("ask").value;
var answer = "I don't know!";
if (val == "how tall are the pyramids")
answer = "146.5 meters";
else if (val == "how tall is the gateway arch")
answer = "630 feet";
else if (val == "how tall is the empire state building")
answer = "6900 feet";
document.getElementById("answer").innerHTML = answer;
}
And in the html, add an answer element like so
<p id="answer"></p>
See CodePen

You want to add another element to your page that can display the results.
In the demo below I have added a span element and set the id attribute to answer.
document.getElementById("button").onclick=function(){
var Q = document.getElementById("ask").value;
var A = document.getElementById("answer");
var Result = "Ask another?";
if (Q=="how tall are the pyramids"){
Result="146.5 meters";
}else if(Q=="how tall is the gateway arch"){
Result="630 feet";
}else if(Q == "how tall is the empire state building"){
Result="6900 feet";
}
A.innerHTML = Result;
}
<span id="answer"></span><br/>
<input type="text" id="ask" />
<button type="button" id="button">Ask</button>
If you don't understand any of the above source code, please leave a comment below.
I hope this helps. Happy coding!

change
document.getElementById("ask").value
to
document.getElementById("ask").innerHTML
or
document.getElementById("ask").innerText

Related

make text disappear after clicking another clickable object

I am making an escape room for my website, I have made a few clickable objects that will display a text. My question is, how do I make text go away after clicking on another clickable item? Everything else in my code works just how I like it except for the text part. Please help
Here is what I have so far.
var hasBluekey = false;
var doorknob = "locked"
var comboLock = "locked"
function tryDoor() {
console.log("You clicked the door");
}
function lookhelp() {
console.log("You clicked on help");
let text = "Who needs help?";
document.getElementById("thehelp").innerHTML = text;
}
function lookClue() {
console.log("You clicked on the clue");
let text = "Hmm, there are letters and numbers circled...";
document.getElementById("theclue").innerHTML = text;
}
function moveTable() {
console.log("You clicked on the table");
let text = "You carefully move away the table with the broken vase";
document.getElementById("thetable").innerHTML = text;
document.getElementById("table").style.display = "none";
}
function tryDoorknob() {
console.log("You clicked the doorknob")
if (hasBluekey == true) {
doorknob = "unlocked";
alert("The doorknob is now unlocked");
checkRoom();
} else {
alert("You need a key");
}
}
function tryComboLock() {
console.log("You clicked the combo lock");
var comboTry = prompt("You enter the combination...");
if (comboTry == "AV70") {
comboLock = "unlocked";
alert("The combination was correct");
checkRoom();
} else {
alert("The combination was incorrect");
}
}
function grabBluekey() {
console.log("You clicked the blue key");
hasBluekey = true;
alert("You picked up the key");
document.getElementById("bluekey").style.display = "none";
}
function checkRoom() {
if (doorknob == "unlocked") {
if (comboLock == "unlocked") {
document.getElementById("next").style.visibility = "visible";
} else {
alert("You push on the door but still need a combination");
}
} else {
alert("You try to turn the door knob but is still locked");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="room">
<img id="door" src="door1.png" onclick="tryDoor()">
<img id="doorknob" src="doorknob1.png" onclick="tryDoorknob()">
<img id="comboLock" src="comboLock.png" onclick="tryComboLock()">
<img id="bluekey" src="blue_key.png" onclick="grabBluekey()">
<img id="clue" src="clue.png" onclick="lookClue()">
<img id="help" src="help.png" onclick="lookhelp()">
<img id="bloodMark" src="bloodMark.png">
<img id="table" src="table.png" onclick="moveTable()">
<img id="window" src="window.png">
<p id="thehelp"></p>
<p id="theclue">
</P>
<p id="thetable"></p>
</div>
<button id="next" onclick="window.location.href
='room2.html';">Proceed</button>
</body>
</html>
Your request seem impossible with an easy answer because you are displaying the text with console.log() I don't think it is possible to update individual lines of output in the console. It is not mentioned anywhere in the documentation. Your easy way out is to display the message or text in a separate element and update that element with the latest text as required. Here is how your code should look like now.
in your html add this code where you want the message to be displayed and style it however you want
<p id="text_message"></p>
And in your javascript code you should replace the console.log("your message"); to this text_message.innerHTML = "your message";
var hasBluekey = false;
var doorknob = "locked"
var comboLock = "locked"
function tryDoor() {
text_message.innerHTML = "You clicked the door";
}
function lookhelp() {
text_message.innerHTML = "You clicked on help";
let text = "Who needs help?";
document.getElementById("thehelp").innerHTML = text;
}
function lookClue() {
text_message.innerHTML = "You clicked on the clue";
let text = "Hmm, there are letters and numbers circled...";
document.getElementById("theclue").innerHTML = text;
}
function moveTable() {
text_message.innerHTML = "You clicked on the table";
let text = "You carefully move away the table with the broken vase";
document.getElementById("thetable").innerHTML = text;
document.getElementById("table").style.display = "none";
}
function tryDoorknob() {
text_message.innerHTML = "You clicked the doorknob";
if (hasBluekey == true) {
doorknob = "unlocked";
alert("The doorknob is now unlocked");
checkRoom();
} else {
alert("You need a key");
}
}
function tryComboLock() {
text_message.innerHTML = "You clicked the combo lock";
var comboTry = prompt("You enter the combination...");
if (comboTry == "AV70") {
comboLock = "unlocked";
alert("The combination was correct");
checkRoom();
} else {
alert("The combination was incorrect");
}
}
function grabBluekey() {
text_message.innerHTML = "You clicked the blue key";
hasBluekey = true;
alert("You picked up the key");
document.getElementById("bluekey").style.display = "none";
}
function checkRoom() {
if (doorknob == "unlocked") {
if (comboLock == "unlocked") {
document.getElementById("next").style.visibility = "visible";
} else {
alert("You push on the door but still need a combination");
}
} else {
alert("You try to turn the door knob but is still locked");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p id="text_message" style="background-color:grey;color:white;"></p>
<div id="room">
<img id="door" src="door1.png" onclick="tryDoor()">
<img id="doorknob" src="doorknob1.png" onclick="tryDoorknob()">
<img id="comboLock" src="comboLock.png" onclick="tryComboLock()">
<img id="bluekey" src="blue_key.png" onclick="grabBluekey()">
<img id="clue" src="clue.png" onclick="lookClue()">
<img id="help" src="help.png" onclick="lookhelp()">
<img id="bloodMark" src="bloodMark.png">
<img id="table" src="table.png" onclick="moveTable()">
<img id="window" src="window.png">
<p id="thehelp"></p>
<p id="theclue">
</P>
<p id="thetable"></p>
</div>
<button id="next" onclick="window.location.href
='room2.html';">Proceed</button>
</body>
</html>
You could try to use ANSI escape codes -- they are really useful for formatting text in a terminal after it's been printed. For this you would want to use cursor controls and erase functions. these are from this tutorial, which was very helpful for a project I made a while ago. Not all of them work on every platform (e.g. replit, not sure if anyone actually uses that though) but overall it's a good system.
example:
console.log("normal text");
//bold, red foreground
console.log("\u001B[1;31m");
console.log("edited text");
(example from the tutorial)
I'm bad at making examples, but I found the two aforementioned sections to be good for quick reference. To truly comprehend how to use it, I suggest that you read through the whole thing.

Javascript - Why won't my incorrect answer counter increment like my correct answer counter does?

I'm trying to increment an incorrect answer counter, for some reason this isn't working. The correct answer counter is working fine so I've tried a similar process in making it a function but no luck. I've tried adding it as separate if statement and also inside the if (selectedAnswer == currentQuestion.answer) statement.
You can ignore the qualifying points because that is part of another counter, I just also want a counter that increments correct and incorrect answers. The correctScore () function works fine, so why doesn't the incorrect one when I place it after correctScore ();?
Hope that makes sense.
let classToApply = 'incorrect-answer';
if (selectedAnswer == currentQuestion.answer) {
qualifyingPointsScore();
correctScore();
classToApply = 'correct-answer';
/*selectedChoice.parentElement.classList.add(classToApply);*/
}
function correctScore() {
correctAnswers += 1;
document.getElementById("correct-score").innerText = correctAnswers;
}
function incorrectScore() {
incorrectAnswers += 1;
document.getElementById("incorrect-score").innerText = incorrectAnswers;
}
</div>
<div class="scores-container">
<div class="scores-area">
<p class="scores">Correct Answers: <span id="correct-score">0</span></p>
<p class="scores">Incorrect Answers: <span id="incorrect-score">0</span></p>
<p class="scores">Total Questions <span id="question-counter">0</span></p>
</div>
</div>
Cheers in advance.
You need to add an else part to the if-statement
...
if (selectedAnswer == currentQuestion.answer) {
qualifyingPointsScore();
correctScore();
classToApply = 'correct-answer';
} else {
incorrectScore();
}
...
if (selectedAnswer == currentQuestion.answer) {
qualifyingPointsScore();
correctScore();
classToApply = 'correct-answer';
/*selectedChoice.parentElement.classList.add(classToApply);*/
}
else{
incorrectScore();
}

making a calculation using JavaScript

Why this isn't working?
I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result..
<script type="text/javascript">
function calculate() {
var calculateit=document.getElementById('disp');
var pluscharacter=/+/;
var matchplus=calculateit.search(pluscharacter);
var inputlength=calculateit.length;
if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
answer=calculateit[0]+calculateit[1];
alert("Your answer is: "+answer+" Is it?");
}
}
</script>
Your if statement isn't a valid condition. Try:
if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)
var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);
calculateit is a Node doesn't have any search() method.
You're doing stuff you don't need to do - just split the string. You also need to get the innerHTML - THAT's the string. Or you can get the "value" from an input field instead. I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. I'd also push the answer into another div. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/9ezky35v/2/
With this HTML:
<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>
You can use this script:
function calculate() {
var calculateit = document.getElementById('disp').innerHTML.trim(),
numbers = calculateit.split('+'),
answerDiv = document.getElementById('answer');
if ( numbers.length > 1 ) {
answer = parseInt(numbers[0]) + parseInt(numbers[1]);
answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
} else {
answerDiv.innerHTML = "I can't calculate that equation.";
}
}
calculate();

How to make an input not case sensitive

I want to know how make it when the user types in something to an input it doesn't have to be the same capitalization as the value for the document.getElementById("spanId").innerHTML = "146.5 meters"; to appear.
HTML
<input id="ask" type="text"
placeholder = "Ex: how tall is the Gateway Arch"
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Ex: how tall is the gateway arch'"
text-align: center/>
JS
document.getElementById("button").onclick = function() {
if (document.getElementById("ask").innerHTML == "how tall are the pyramids") {
document.getElementById("spanId").innerHTML = "146.5 meters";
} else if (document.getElementById("ask").value == "how tall is the gateway arch") {
document.getElementById("spanId").innerHTML = "630 feet";
} else if (document.getElementById("ask").value == "how tall is the empire state building") {
document.getElementById("spanId").innerHTML = "1,454 feet";
}
}
First, use value instead of innerHTML for input fields
Second, convert both side lowercase or uppercase during comparing
Try like this
var ask=document.getElementById("ask").value.toLowerCase();
if (ask =="how tall are the pyramids")
Or like this
var ask=document.getElementById("ask").value.toUpperCase();
if (ask =="how tall are the pyramids".toUpperCase())

Looping through array using a button

Ok, in essence I want to create a short quiz that has a next and previous button. I want to loop through two arrays, questions and choices, and have a score at the end. I have read chapters on the DOM and Events and it is just not clicking apparently.
Really I need a little bit of code that shows a concrete example of how to manipulate the DOM. What I have so far are only the arrays, and a function declaring that x is in fact getting my element by id. haha.
Sorry I don't have more code to give. I tried to attach the id to a paragraph, and then get it by it's id and document.write the array, but that replaces the button. If you run the code below you'll see what I'm saying.
<!DOCTYPE html>
<html>
<head>
<title>Bom</title>
</head>
<body>
<input type="button" value="Iterate" id="myButton" onclick="iter_onclick()">
<p id="qArray">Some Text</p>
<script>
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","","The Smurf Girl"]];
function iter_onclick () {
var x = document.getElementById("qArray");
document.write("Hello World");
}
</script>
</body>
</html>`
Like I said, this is my first attempt at truly manipulating the DOM, and I know what I want to do. I just don't know how to do it. I am understanding all the syntax and events and objects and such. But, I'm not really sure how to apply it. Also, no Jquery. I want to know how to create applications with Javascript and then work my way into Jquery. Thanks people.
This will loop through your questions, hope this helps you to proceed.
var qArray = ["Who is my dog?",
"who is the prez?",
"Who is my girlfriend?",
"Who am I?"];
var cArray = [
["Bill", "Billy", "Arnold", "Tyler"],
["Oz", " Buffon", "Tupac", "Amy"],
["Tony Blair", "Brack Osama", "Barack Obama", "Little Arlo"],
["Emma Stone", "Tony the Tiger", "Amy Dahlquist", "The Smurf Girl"]
];
var index = 0;
function iter_onclick() {
//if this is the last question hide and displays quiz ends
if (index >= qArray.length) {
document.getElementById('qArray').innerHTML = '<div>Quiz End, Thank you</div>'
document.getElementById('myButton').style.visibility = 'hidden ';
return false;
}
var html = ' <div> ' + qArray[index] + ' </div> <div>';
for (var i = 0; i < cArray[index].length; i++) {
html += '<label><input type="radio" name="ans" value="'
+ cArray[index][i] + '"/ > ' + cArray[index][i] + ' </label>';
}
html += '</div > ';
document.getElementById('qArray').innerHTML = html;
index++;
}
Here's a very basic example you can work from. This modifies the existing DOM items. You cannot use document.write() on a document that is already loaded or it will clear everything you have and start over and it's not the most efficient way to put content into the DOM.
This example has a number of fields on the page, it loads a question and then checks the answer when you press the next button.
HTML:
<div id="question"></div>
<input id="answer" type="text"><br><br>
<button id="next">Next</button> <br><br><br>
Number Correct So Far: <span id="numCorrect">0</span>
Javascript (in script tag):
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","Amy Dahlquist","The Smurf Girl"]];
var questionNum = -1;
var numCorrect = 0;
function loadQuestion() {
++questionNum;
if (questionNum >= qArray.length) {
alert("all questions are done");
} else {
document.getElementById("question").innerHTML = qArray[questionNum];
document.getElementById("answer").value = "";
}
}
loadQuestion();
function checkAnswer() {
var answer = document.getElementById("answer").value.toLowerCase();
var allowedAnswers = cArray[questionNum];
for (var i = 0; i < allowedAnswers.length; i++) {
if (allowedAnswers[i].toLowerCase() == answer) {
return true;
}
}
return false;
}
document.getElementById("next").addEventListener("click", function(e) {
if (checkAnswer()) {
++numCorrect;
document.getElementById("numCorrect").innerHTML = numCorrect;
loadQuestion();
} else {
alert("Answer is not correct");
}
});
Working demo: http://jsfiddle.net/jfriend00/gX2Rm/

Categories

Resources