I can't seem to find the documentation that discusses this, so I thought maybe someone on here could help. I want to write a javascript if/else function that triggers multiple events. My code is a little rough, but I think it should look like:
function getFruit() {
var x = document.getElementById("myinput").value;
var score;
var picture;
if (x === "Apple") {
score = "A" || pciture = "http://exampple.com/assets/apple.jpg";
else(x === "Banana") {
score = "B" || picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").image.src = picture;
}
<input type="text" id="myinput">
<p id="text"></p>
<img id="display"></img>
You just need them on different lines. There is no reason for doing the ||.
function getFruit() {
var x = document.getElementById("myinput").value;
var score;
var picture;
if (x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
}
else if (x === "Banana") {
score = "B";
picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").image.src = picture;
}
Multiple errors of syntaxis in your code.
This is a correct if/else statement
if (x === "Apple") {
...
} else {
...
}
function getFruit() {
var x = document.getElementById("myinput").value;
var score;
var picture;
if (x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
} else {
score = "B";
picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").src = picture;
}
<input type="text" id="myinput">
<p id="text"></p>
<img id="display" src="">
<button onclick="getFruit()">Check</button>
If you want to have a cleaner code, and avoid to have the same variable assignment all over the place you should wrap everything in an Object and use the input's value to access the properties
// Call this function differently renderFruit, or loadFruit, etc
function getFruit() {
var x = document.getElementById("myinput").value;
var fruits = {
Apple: {
score: 'A',
picture: 'https://via.placeholder.com/300x120?text=Apple'
},
Banana: {
score: 'B',
picture: 'https://via.placeholder.com/300x120?text=Banana'
}
};
var f = fruits[x];
document.getElementById("text").innerHTML = f && f.score;
document.getElementById("display").src = f && f.picture;
// Please don't name getSomething to a function that does not
// have a return statement e.g.: return f;
}
<input type="text" id="myinput" onchange="getFruit()">
<p id="text"></p>
<img id="display" />
Related
<!DOCTYPE html>
<html>
<body>
<p id="Image"></p>
Basically what im tryijngto do s
One fix I'd recommend would be splitting your logic into two functions, one the user clicks to check their answer, and one they click to see the next question. This will allow you to display the congrats message on the screen rather than in an alert. Here is that in action:
let score = 0;
let questionsAsked = 0;
const button = document.querySelector('button');
const input = document.getElementById('userInput');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const checkMessage = document.getElementById('check-message');
checkMessage.set = message => checkMessage.innerHTML = message;
checkMessage.clear = message => checkMessage.innerHTML = '';
const options = {
chad: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/600x400/000000/efebe9/?text=John'
}
function askQuestion() {
checkMessage.clear();
input.value = '';
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
document.getElementById('image').innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
button.setAttribute('onclick','checkAnswer()');
button.textContent = 'Check Your Answer!';
}
function checkAnswer() {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
checkMessage.set('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
gameScore.add();
} else {
checkMessage.set('SORRY, IT WAS INCORRECT');
gameScore.subtract();
}
questionsAsked++;
button.setAttribute('onclick','askQuestion()');
button.textContent = 'Next Question';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="checkAnswer()">Start Game!</button>
<input id="userInput" type="text" />
<p id="check-message"></p>
If you would prefer to keep everything in one function and use alerts for the congrats message, you can do so by keeping track of then number of questions asked, and not instantly checking the answer on the first load, like this:
let score = 0;
let questionsAnswered = -1;
const imageContainer = document.getElementById('image');
const button = document.querySelector('button');
const input = document.getElementById('user-input');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const options = {
chad: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/250x250/000000/efebe9/?text=John'
}
function askQuestion() {
questionsAnswered++;
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
if (questionsAnswered) {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
gameScore.add();
alert('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
} else {
gameScore.subtract();
alert('SORRY, IT WAS INCORRECT');
}
questionsAnswered++;
}
imageContainer.innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
input.value = '';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="askQuestion()">Check Answer!</button>
<input id="user-input" type="text" />
Both solutions would work fine with alerts, though the first solution offers some greater flexibility for any functions you make want to perform in between questions. One other main fix there was to make here was to check change the image after checking the answer, and also making sure to actually fun the function in the beginning using askQuestion() in this case. I also added a couple of handy functions gameScore.add() and gameScore.subtract() to ease future use.
You can pass in other integers such as gameScore.add(2) if you every wanted to have double-weighted questions. I also added a Math.max() line to ensure the score never passes below 0. You can remove this if you would like the player's score to pass into negative numbers.
Here is a working version of your game. To begin: <br>
1.Your code was not modifying the src of the image (thus no image appears) <br>
1a. I am modifying the src attribute associated with the `img` tag now. <br>
1b. `document.getElementById("Image").src = randomPhoto;` <br>
2. `theArrayArray` does not exist. I updated the variable to `theArray` <br>
3. To display an image when the game begins you need a handler. <br>
3a. I added the `button` to handle that <br>
4. Unless you want the user to type out `.jpg` you need to remove .jpg <br>
4a. `randomPhoto = randomPhoto.replace(".jpg", "");` <br>
<img id="Image" src="#" width="250" height="250">
<br>
<br>
<input id="userInput" type="text">
<br>
<br>
<button type="button" id="btn" onclick="startGame()">Start Game</button>
<span id="GameScore">Score:</span>
<script>
let score = 10;
var Chad = "Chad.jpg";
let begin = 1;
let thePhoto;
var someArray = [ Chad, Bob
];
function startGame() {
if (start == 0) {
for (var l = 2; i < 3; i--) {
randomPhoto = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = randomPhoto;
document.getElementById("btn").innerHTML = "Submit";
start = 1;
}
} else {
randomPhoto = randomPhoto.replace(".jpg", "Insert");
}
else {
for (var x = 0; i < 3; i++) {
TheName = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = theName;
alert("No");
scorex = score-1;
}
document.getElementById("theScore").innerHTML="Score: "+score;
</script>
</body>
</html>
I'm trying to create a simple game where you have to answer the correct answer from a calculation.
I already have the function to generate random calculations, but i don't know how to compare it with the result which the user writted.
I tried to make the if, so when the user press the submit button, then the app will try to determine if that's the correct answer.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var question = document.getElementById("textQuestion");
var answer = document.getElementById("textAnswer");
function rollDice() {
document.form[0].textQuestion.value = numArray[Math.floor(Math.random() * numArray.length)];
}
function equal() {
var dif = document.forms[0].textQuestion.value
if (dif != document.forms[0].textAnswer.value) {
life--;
}
}
<form>
<input type="textview" id="textQuestion">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
</form>
<input type="button" name="start" onclick="">
document.forms[0].textQuestion.value looking for an element with name=textQuestion, which doesn't exist. Use getElementById instead or add name attribute (needed to work with the input value on server-side).
function equal() {
if (document.getElementById('textQuestion').value != document.getElementById('textAnswer').value) {
life--; // life is undefined
}
}
// don't forget to call `equal` and other functions.
This is probably what you're looking for. I simply alert(true || false ) based on match between the random and the user input. Check the Snippet for functionality and comment accordingly.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var questionElement = document.getElementById("textQuestion");
var answerElement = document.getElementById("textAnswer");
function rollDice() {
var question = numArray[Math.floor(Math.random() * numArray.length)];
questionElement.setAttribute("value", question);
}
//rolldice() so that the user can see the question to answer
rollDice();
function equal()
{
var dif = eval(questionElement.value); //get the random equation and evaluate the answer before comparing
var answer = Number(answerElement.value); //get the answer from unser input
var result = false; //set match to false initially
if(dif === answer){
result = true; //if match confirmed return true
}
//alert the match result
alert(result);
}
document.getElementById("start").addEventListener
(
"click",
function()
{
equal();
}
);
<input type="textview" id="textQuestion" value="">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
<input type="button" id="start" value="Start">
There's more I would fix and add for what you're trying to achieve.
First of you need a QA mechanism to store both the question and the correct answer. An object literal seems perfect for that case: {q: "", a:""}.
You need to store the current dice number, so you can reuse it when needed (see qa_curr variable)
Than you could check the user trimmed answer equals the QA.a
Example:
let life = 10,
qa_curr = 0;
const EL = sel => document.querySelector(sel),
el_question = EL("#question"),
el_answer = EL("#answer"),
el_check = EL("#check"),
el_lives = EL("#lives"),
qa = [{
q: "Calculate 10 / 2", // Question
a: "5", // Answer
}, {
q: "What's the result of 5 x 5",
a: "25"
}, {
q: "5 - 6",
a: "-1"
}, {
q: "Subtract 20 from 70",
a: "-50"
}];
function rollDice() {
qa_curr = ~~(Math.random() * qa.length);
el_question.textContent = qa[qa_curr].q;
el_lives.textContent = life;
}
function checkAnswer() {
const resp = el_answer.value.trim(),
is_equal = qa[qa_curr].a === el_answer.value;
let msg = "";
if (resp === '') return alert('Enter your answer!');
if (is_equal) {
msg += `CORRECT! ${qa[qa_curr].q} equals ${resp}`;
rollDice();
} else {
msg += `NOT CORRECT! ${qa[qa_curr].q} does not equals ${resp}`;
life--;
}
if (life) {
msg += `\nLives: ${life}`
} else {
msg += `\nGAME OVER. No more lifes left!`
}
// Show result msg
el_answer.value = '';
alert(msg);
}
el_check.addEventListener('click', checkAnswer);
// Start game
rollDice();
<span id="question"></span><br>
<input id="answer" placeholder="Your answer">
<input id="check" type="button" value="Check"> (Lives:<span id="lives"></span>)
The above still misses a logic to not repeat questions, at least not insequence :) but hopefully this will give you a good start.
I have this if else script. It is currently returning an image to variable R if the function is true. I need it to ALSO return a numerical result as well as the image. So R2 = 1 if true, 0 if false. I'm not sure how to set this up.
Question: what is 50% + 50%?
<input type="text" length="3" id="ANSWER1B">
<input type="button" value="Enter" onclick="Q1B()">
<!--QUESTION 1B-->
<script>// <![CDATA[
function Q1B()
{
var A = document.getElementById("ANSWER1B").value;
var A;
if (A == '100%') {
R = '<img src="http://leowestonvfx.com/wp-content/uploads/2016/02/rock-hand.png"/>';
} else {
R = '<img src="http://leowestonvfx.com/wp-content/uploads/2016/02/thumbs-down.png"/>'
}
document.getElementById("RETURN1B").innerHTML = R;
}
// ]]></script>
<p id="RETURN1B">
I've found other posts on this subject but I don't understand the answers very well. My coding level is pretty much day 1. Please help.
You can use that function for returning multiple value
public int Multiple returns(int m, int n, ref int max)
{
if (m < n)
{
enter code here
max=m;
return n;
}
else
{
max=n;
return m;
}
}
Just take two seperate variables and replace them in different div's seperately.
function Q1B()
{
var A = document.getElementById("ANSWER1B").value;
var number;
if (A == '100%') {
R = '<img src="http://leowestonvfx.com/wp-content/uploads/2016/02/rock-hand.png"/>';
number = 1;
} else {
R = '<img src="http://leowestonvfx.com/wp-content/uploads/2016/02/thumbs-down.png"/>'
number = 0;
}
document.getElementById("RETURN1B").innerHTML = R;
document.getElementById("Number").innerHTML = number;
}
Question: what is 50% + 50%?
<input type="text" length="3" id="ANSWER1B">
<input type="button" value="Enter" onclick="Q1B()">
<p id="RETURN1B">
<p id="Number">
You should make R an object. You can then have an R1 value which is the picture, and an R2 value which is numeric (though it would be better to name them more descriptively). You can then return R at the end of your function.
function Q1B()
{
var A = document.getElementById("ANSWER1B").value;
var R = {};
if (A == '100%') {
R.R1 = '<img src="http://leowestonvfx.com/wp-content/uploads/2016/02/rock-hand.png"/>';
R.R2 = 1;
} else {
R.R1 = '<img src="http://leowestonvfx.com/wp-content/uploads/2016/02/thumbs-down.png"/>';
R.R2 = 0;
}
return R;
}
here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.
I'm trying to create a guessing game that if the user enters a number into an input field and click a button, a text shows up saying if the number is bigger or smaller than a random number that's been created by JavaScript. I seem to have figured out everything else, but I'm having a hard time getting the value that is entered into the input field.
I'd appreciate your help.
<div class="wrap" >
Project: Guessing Game
<input type="text" name="inputField" value="" id="inputField"/>
<button id="guess">Guess!</button>
<br>
<p id="result"></p>
</div>
<script type="text/javascript" charset="utf-8">
var $ = function(selector) {
return document.querySelector(selector);
};
var randomRange = function(min,max){
return Math.random(((Math.random()*(max-min))+min));
};
var randomNumber = randomRange(1,4);
var myButton = $("#guess");
var myNumber = $("#inputField").value;
var myResult = $("#result");
if ( myNumber > randomNumber) {
myButton.onclick = function () {
myResult.innerHTML += "Your number is bigger than the random number";
}
}
else if ( myNumber < randomNumber){
myButton.onclick = function () {
myResult.innerHTML += "Your number is smaller than the random number";
}
}
else if ( myNumber === randomNumber ){
myButton.onclick = function () {
myResult.innerHTML += "Your number matches the random number";
}
}
</script>
Your input is being read when there is no data, and when you click, you don't check if the data has changed. You should place the decision blocks to check the input inside the event handler, like this:
myButton.onclick = function () {
var myNumber = $("#inputField").value;
myNumber = parseInt(myNumber, 10);
if ( myNumber > randomNumber) {
myResult.innerHTML = "Your number is bigger than the random number";
} else if ( myNumber < randomNumber){
myResult.innerHTML = "Your number is smaller than the random number";
} else if ( myNumber === randomNumber ){
myResult.innerHTML = "Your number matches the random number";
}
}
var $ = function(selector) {
return document.querySelector(selector);
};
var randomRange = function(min,max){
return Math.round(((Math.random()*(max-min))+min));//notice here,Math.round
};
var randomNumber = randomRange(1,4);
var myButton = $("#guess");
var myNumber = $("#inputField");
var myResult = $("#result");
myButton.onclick = function(){
var val = parseInt(myNumber.value, 10);
if(val < randomNumber){
//smaller code
}else if(val > randomNumber){
//bigger code
}else{
//equal code
}
}