I'm trying to create a very basic JS quiz game. Almost everything works except for a single piece of code. When you hit the third radio input at the very last question, you have to double click the button in order to make true the "if else" statement. If I check the first two radio buttons everything works correctly. I don't understand why.
// VARIABLES
var all = {
question: ['Quante dita ha una mano?', "Qual รจ la capitale del Marocco", "Cosa si mangia in Spagna?" ],
response: [['uno', 'due', 'cinque'],['Marrakesh', 'Dubai', 'Roma'], ['Paella', 'Salsiccia', 'Fish']]
}
var i = 0;
var storage = [];
// TITLE
var title = document.getElementById("title");
//LABELS
var label1 = document.getElementById('risposta1');
var label2 = document.getElementById('risposta2');
var label3 = document.getElementById('risposta3');
// INPUTS
var inputs = document.querySelectorAll('input[type="radio"]')
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
var input3 = document.getElementById('input3');
// DISPLAY ANSWER
function displayAnswer(){
if(all.response[i] != undefined){
title.innerHTML = all.question[i];
label1.innerHTML = all.response[i][0];
label2.innerHTML = all.response[i][1];
label3.innerHTML = all.response[i][2];
}
}
displayAnswer();
document.querySelector('#btn').addEventListener("click", function(e){
inputs.forEach(function(input){
if(i <= (all.question.length - 1)){
if(input.checked === true){
console.log(e);
console.log(input3);
console.log(input.value);
storage.push(input.value);
i++;
displayAnswer();
console.log(i);
}
}
else {
console.log("Your score is: " + storage);
document.getElementById( 'content' ).style.display = 'none';
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="content">
<h1 id="title"></h1>
<label id="risposta1"></label>
<input id="input1" type="radio" name="test" value="1" ><br>
<label id="risposta2"></label>
<input id="input2" type="radio" name="test" value="2" ><br>
<label id="risposta3"></label>
<input id="input3" type="radio" name="test" value="3"> <br>
<button id="btn">Invia</button>
</div>
<script src="app.js"></script>
</body>
</html>
In the console there is no errors.
Related
In the code below 'len' is the length of text in a tag, the user enters a letter in a textbox, and inside 'result', with the help of .indexof() I am storing the index number of the letter present in the paragraph and then printing that letter in another tag.
But this loop only runs once whereas I want it to run until the statement in the while loop is true.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Find letter:</p>
<form id="chk" method="post">
<label for="scen">Enter a scentence</label>
<!--<input type="text" name="scen" id="scen" placeholder="Enter a scentence">-->
<p id='scen'>Hello my friend</p>
<br><br>
<label for="letter">Enter the letter</label>
<input type="text" name="letter" id="letter" placeholder="Enter a letter" min="1">
<br>
<button type="button" onClick="myFunction()">Submit</button>
</form>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script >
function myFunction(){
var scen = document.getElementById('scen').innerHTML;
var spa = ' ';
var scen1 = scen.split(" ").join(spa);
var letter = document.getElementById('letter').value;
let err = "The letter does not exist in the sentence"
let result = scen.indexOf(letter);
var len = scen.length;
var a = 3;
var k = 0
for(var i = 0; i < scen1.length; i++)
{
document.getElementById('demo').innerHTML += '<span id="w' + i + '">' + scen1[i] + '</span>'
}
while(k <= len){
if(result>=0){
document.getElementById('demo3').innerHTML = scen.substring(result,result+1);
document.getElementById('demo').innerHTML = len;
}
else{
document.getElementById('demo2').innerHTML = err;
a--;
document.getElementById('demo').innerHTML = a;
break;
}
if(a==0){
window.alert('game over');
}
k++;
}
}
</script>
</body>
</html>
Because of the break condition in Else part of your code is making code to exit from loop.
Please see below code and comments which I have added in your code... and let me know...
function myFunction() {
var scen = document.getElementById('scen').innerHTML;
var spa = ' ';
var scen1 = scen.split(" ").join(spa);
var letter = document.getElementById('letter').value;
let err = "The letter does not exist in the sentence"
let result = scen.indexOf(letter);
var len = scen.length;
var a = 3;
var k = 0
for (var i = 0; i < scen1.length; i++) {
document.getElementById('demo').innerHTML += '<span id="w' + i + '">' + scen1[i] + '</span>'
}
while (k <= len) {
//console.log("Loop iteration ->",k); /*you can uncomment this statement to debug the loop is working or not *?
if (result >= 0) {
document.getElementById('demo3').innerHTML = scen.substring(result, result + 1);
document.getElementById('demo').innerHTML = len;
} else {
document.getElementById('demo2').innerHTML = err;
a--;
document.getElementById('demo').innerHTML = a;
// break; /* Commented this line so that your loop will run*/
}
if (a == 0) {
window.alert('game over');
}
k++;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Find letter:</p>
<form id="chk" method="post">
<label for="scen">Enter a scentence</label>
<!--<input type="text" name="scen" id="scen" placeholder="Enter a scentence">-->
<p id='scen'>Hello my friend</p>
<br><br>
<label for="letter">Enter the letter</label>
<input type="text" name="letter" id="letter" placeholder="Enter a letter" min="1">
<br>
<button type="button" onClick="myFunction()">Submit</button>
</form>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
</body>
</html>
Remove the break. It's breaking you out of the loop.
I'm trying to make a menu for a Memory Game type game. I created the html page that contains a form consisting of 2 radio buttons with different values. On the submit input I called my function from the javascript file. And in the js file I created an if else function to redirect me, but it doesn't work.
Code:
`
let button = document.getElementById("button");
let solo = document.getElementById("solo");
let multiplayer = document.getElementById("multiplayer");
let level1 = document.getElementById("3x4");
let level2 = document.getElementById("4x4");
let radio1 = document.getElementsByName("radio1");
let radio2 = document.getElementsByName("radio2");
// button.addEventListener("click", gameMenu);
function gameMenu() {
if ((radio1.value = "solo") && (radio2.value = "3x4")) {
// location.href = "sg_34.html";
console.log("solo/3x4");
}
else if ((radio1.value = "solo") && (radio2.value = "4x4")) {
// location.href = 'sg-44.html';
console.log("solo/4x4");
}
else if ((radio1.value = "multiplayer") && (radio2.value = "3x4")) {
// location.href = 'mp-34.html';
console.log("mp/3x4");
}
else if ((radio1.value = "multiplayer") && (radio2.value = "4x4")) {
// location.href = "mp-44.html";
console.log("mp/4x4");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<link rel="stylesheet" href="./css/styleIndex.css">
<title>Memorizer JS</title>
</head>
<body>
<div class="container">
<h1>Memorizer JS</h1>
<form class="form menu">
<section class="game cf">
<h2>Choose game mode:</h2>
<input type="radio" name="radio1" id="solo" value="solo">
<label class="solo-label four col" for="solo">Solo</label>
<input type="radio" name="radio1" id="multiplayer" value="multiplayer">
<label class="multiplayer-label four col" for="multiplayer">With a friend</label>
</section>
<section class="level cf">
<h2>Level:</h2>
<input type="radio" name="radio2" id="3x4" value="3x4">
<label class="3x4-label four col" for="3x4">3x4</label>
<input type="radio" name="radio2" id="4x4" value="4x4">
<label class="4x4-label four col" for="4x4">4x4</label>
</section>
<input class="submit" id="button" type="submit" value="Play" onclick="gameMenu()">
</form>
</div>
<script src="./scripts/index.js"></script>
</body>
</html>
`
Code pen: https://codepen.io/sebastian-mihai-ciuc/pen/BaVagNM
I created the conditions in an if else structure to check the values in the radio buttons. I expected it to redirect me to other pages or at least display the cases in the console.log.
You should remove form tags for not reloading the window
I'm trying to create a make addEventListener function to a button, when click it should print the value of the input.
but I'm getting an error message:
Cannot read properties of null (reading 'addEventListener')
let plus = document.getElementById('btnPlus');
let minus = document.getElementById('btnMinus');
let multiplay = document.getElementById('btnMultiplay');
let divide = document.getElementById('btnDivide');
let inputOne = document.getElementById('firstNum');
let inputTwo = document.getElementById('secondNum');
// if + button click display in result inputOne + inputTwo
plus.addEventListener('click', function() {
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
console.log(valueOne);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calcultaor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="mainHeader">
<h1> Calculator </h1>
<label for="">Enter First Number</label>
<input type="text" class="firstNum"> <br/>
<label for="">Enter Second Number</label>
<input type="text" class="secondNum"><br/>
<button class="btnPlus">+</button>
<button class="btnMinus">-</button>
<button class="btnMultiplay">*</button>
<button class="btnDivide">/</button>
<h2> The Result Is <span class=span_result /> </h2>
</div>
<script src="app.js"></script>
</body>
</html>
getElementById works only with ID not with classes. Review your HTML
Because this code does not contain an id
<button class="btnPlus">+</button>
If you want get an element by id, the element must contain the id.
Try this
<button id="btnPlus">+</button>
The addEventListener() method attaches an event handler to an element.
You don't have an element with id btnPlus.
Now the below code is running fine.
You have to define the variable as a Number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="mainHeader">
<h1>Calculator</h1>
<label for="">Enter First Number</label>
<input type="text" id="firstNum" /> <br />
<label for="">Enter Second Number</label>
<input type="text" id="secondNum" /><br />
<button id="btnPlus">+</button>
<button id="btnMinus">-</button>
<button id="btnMultiplay">*</button>
<button id="btnDivide">/</button>
<h2>The Result Is <span id="span_result" /></h2>
</div>
<p id="demo">
<script>
let plus = document.getElementById("btnPlus");
let minus = document.getElementById("btnMinus");
let multiplay = document.getElementById("btnMultiplay");
let divide = document.getElementById("btnDivide");
let inputOne = document.getElementById("firstNum");
let inputTwo = document.getElementById("secondNum");
const element = plus;
element.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)+ Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element2 = minus;
element2.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)- Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element3 = multiplay;
element3.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)* Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element4 = divide;
element4.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)/ Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
</script>
</p>
</body>
</html>
From input i enter numbers in the input text, then i have 5 buttons that have functions on them i tried to make the first button to minus the number by 1 but i don't know when i click the number get -1 but it doesn't show changes to the input box. How can i fix this i mean don't know how to do it because i tried using number.innerHTML = number-=1 but it doesn't work ? Here is my html and javascript code:
var number = document.getElementById("number");
number = number.value;
function minus() {
number.value = number -= 1;
console.log(number);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<input type="text" id="number" id="output">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
</body>
</html>
Ok let's think logically here
var number = document.getElementById("number");
number = number.value;
function minus() {
number.value = number -= 1;
console.log(number);
}
first you're assigning the HTML ELEMENT itself to the var "number", then you're changing the value of the "number" var to the value of the HTML element, so then number.value = number - 1 is trying to set the property of "value" of a number object, which doesn't make sense, because it's not connected to the HTML element anymore
Just make two variables it should be fine, like
var number = document.getElementById("number");
var numberValue = number.value;
function minus() {
numberValue = number.value;
number.value = numberValue -= 1;
console.log(number,numberValue);
}
or alternatively, you only need one variable total, and you don't need to reassign it to "number.value", but the only thing is that this way there's no guarantee that number.value is a number at all, but when you set it to a variable first, like above, you can check if(!isNaN) or something similar, but still, if we want to assume only numbers will ever be entered, we can do something like
var number = document.getElementById("number");
function minus() {
number.value = number.value -= 1;
console.log(number,number.value);
}
Try this instead.
var number = document.getElementById("number");
function minus() {
number.value = number.value -= 1;
console.log(number);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<input type="text" id="number" id="output">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
</body>
</html>
I want the script to save the value of the text only when it's checked.
If possible I also want to save the value of it only when it's clicked as a variable so I can do this for example
Name: {here the variable} #if checked
<html>
<head>
<title>Feedback</title>
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
function addTextHTML()
{
document.addtext.name.value = document.addtext.name.value + ".html"
}
function addTextTXT()
{
document.addtext.name.value = document.addtext.name.value + ".txt"
}
</script>
</head>
<body>
<form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">
<input type="checkbox" name="text" id="test" value=name>
<label for="test">Test</label>
<br>
<input type="text" name="name" value="" placeholder="File Name">
<input type="submit" onClick="addTextHTML();" value="Save As HTML">
<input type="submit" onClick="addTexttxt();" value="Save As TXT">
</form>
</body>
</html>
Try to use break;. But it will give error and you'll be able to see it on console.
So try something like this;
var text = "";
var a;
for (a = 1; a < 2; a++){
//code will be here which gets in the loop
text += "Working";
}
document.getElementById("demo").innerHTML = text;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width = device-width, initial-scale = 1.0">
<meta http-equiv="X-UA-Compatible" content = "ie=edge">
<title> Keat </title>
</head>
<body>
<p id="demo"></p>
</body>
</html>
This will make loop to but it will restrict the loop.