I am trying to make a simple guessing number game. I cannot get the function to operate correctly, or display my messages to the user. Am I not using the innerHTML correctly? I also want the game to reload when the number is guessed correctly, I am not sure if it works because the game will not operate.
var number = 0;
var output = document.getElementById("output").innerHTML;
function pickInteger() {
"use strict";
number = Math.floor(Math.random() * 10 + 1);
}
function checkGuess() {
"use strict";
var guess = document.getElementById("guess").value;
if (guess == number) {
alert(number + " " + "Is the correct number!");
output = "";
pickInteger();
}
if (guess < number); {
output = "The number I am thinking of is higher than" + guess;
} else if (guess > number); {
output = "The number I am thinking of is lower than" + guess;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Guess the Number</title>
<link rel="stylesheet" href="css/Lab6.css" />
<script type="text/javascript" src="script/Lab6.js"></script>
</head>
<body onload="pickInteger()">
<div>
<h2><strong>Guess the Number</strong></h2>
</div>
<br/>
<div id="formDiv">
<form name="AForm" method="get">
<p>The computer has picked a number between 1 - 99, you must choose the correct number to win the game. When you guess the right number the game will restart.<br/>
</p>
<div id="bodyDiv">
<p> Your guess is:
<input id="guess" type="text" size="1" name="theData" value="" autofocus/>
<input type="button" name="mybutton" value=" Guess " onclick="checkGuess()">
</p>
<p id="output">
</p>
</div>
</form>
</div>
</body>
</html>
you had a semicolon if (guess < number); and else if (guess > number); which is wrong just remove it and it will start working, see below your code
var number = 0;
var output = document.getElementById("output").innerHTML;
var consolecounter = 0;
function pickInteger() {
"use strict";
number = Math.floor(Math.random() * 10 + 1);
}
$(document).ready(function() {
pickInteger();
$("form[name='AForm']").on('submit', function(e) {
"use strict";
e.preventDefault();
var guess = parseInt(document.getElementById("guess").value);
if (guess == number) {
alert(number + " " + "Is the correct number!");
output = "";
pickInteger();
}
if (guess < number) {
console.log("The number I am thinking of is higher than " + guess);
consolecounter++;
} else if (guess > number) {
console.log("The number I am thinking of is lower than " + guess);
consolecounter++;
}
clearConsole(consolecounter);
})
})
function clearConsole(consolecounter) {
(consolecounter == 3) && (setTimeout(function() {
console.clear();
consolecounter = 0;
}, 2000));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Guess the Number</title>
</head>
<body>
<div>
<h2><strong>Guess the Number</strong></h2>
</div>
<br/>
<div id="formDiv">
<form name="AForm" method="get">
<p>The computer has picked a number between 1 - 99, you must choose the correct number to win the game. When you guess the right number the game will restart.<br/>
</p>
<div id="bodyDiv">
<p> Your guess is:
<input id="guess" type="text" size="1" name="theData" value="" autofocus/>
<input type="submit" name="mybutton" value=" Guess ">
</p>
<p id="output">
</p>
</div>
</form>
</div>
</body>
</html>
Related
The game works fine, but for some reason it displays “-1 guesses left” when the game is over right after I click on the “play again” button and the game refreshes. The user only gets three guesses and the game should stop notifying guesses left after the remaining guesses are 0.
// guess btn handler
guessBtn.addEventListener("click", function() {
// guess value
let guess = parseInt(guessInput.value);
// guess validator
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a number between ${min} and ${max}`, "red");
} else if (guess === winningNum) {
gameOver(true, `Winner! ${winningNum} is correct`);
playAgain();
} else {
guessesLeft -= 1;
if (guessesLeft === 0) {
gameOver(false, `Game Over! ${winningNum} was the number`);
playAgain();
} else
<!-- begin snippet: js hide: false console: true babel: false -->
<!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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<title>Document</title>
</head>
<body>
<div class="container">
<h1>Number Guesser</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter guess">
<input type="submit" value="submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
{
setMessage(${guessesLeft} guesses left, "red");
}
}
});
// play again
function playAgain() {
guessBtn.value = "Play Again";
guessBtn.className += "play-again";
}
// game over
function gameOver(won, msgOutput) {
let color;
won === true ? color = "green" : color = "red";
guessInput.disabled = true;
guessInput.style.borderColor = color;
setMessage(msgOutput, color);
}
// generate random winning number
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// message box
function setMessage(msgOutput, color) {
msg.style.color = color;
msg.textContent = msgOutput;
}
<div class="container">
<h1>Number Guesser</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter guess">
<input type="submit" value="submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Have a look at the below code. Here I've added some more code on play again button
min=10;
max = 20;
winningNum = 13;
guessesLeft = 3;
// guess btn handler
const guessBtn = document.getElementById("guess-btn");
guessInput = document.getElementById("guess-input");
const msg = document.getElementsByClassName("message")[0];
guessBtn.addEventListener("click", function(e) {
if(e.target.value === "submit"){
// guess value
let guess = parseInt(guessInput.value);
// guess validator
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a number between ${min} and ${max}`, "red");
} else if (guess === winningNum) {
gameOver(true, `Winner! ${winningNum} is correct`);
playAgain();
} else {
guessesLeft -= 1;
if (guessesLeft === 0) {
gameOver(false, `Game Over! ${winningNum} was the number`);
playAgain();
} else {
setMessage(`${guessesLeft} guesses left`, "red");
}
}
}else{
guessBtn.value = "submit";
guessInput.value="";
guessInput.disabled = false;
guessInput.style.borderColor = "";
setMessage("");
}
});
// play again
function playAgain() {
guessBtn.value = "Play Again";
guessBtn.className += "play-again";
guessesLeft = 3;
}
// game over
function gameOver(won, msgOutput) {
let color;
won === true ? color = "green" : color = "red";
guessInput.disabled = true;
guessInput.style.borderColor = color;
setMessage(msgOutput, color);
}
// generate random winning number
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// message box
function setMessage(msgOutput, color) {
msg.style.color = color;
msg.textContent = msgOutput;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>React Boilerplate</title>
</head>
<body>
<div class="container">
<h1>Number Guesser</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter guess">
<input type="submit" value="submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
</body>
</html>
I'm trying to make a quiz, here is the html :
<!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>English Test</title>
<link rel="stylesheet" href="testCss.css">
</head>
<body>
<br>
<div style="font-size:20px">
<p>Please choose the correct answer and at the end tap the score button. </p>
<br>
<div>
2. I
<select id="question2">
<option value="_">_</option>
<option value="Am">am</option>
<option value="Is">is</option>
<option value="Are">are</option>
</select>
22 years old.
<span id="question2_answer"></span>
</div>
<br>
<br>
<div>
101. When can we meet again?
<span id="question101_answer"></span>
<div>
<input type="radio" name="question101" > When are you free?<br>
<input type="radio" name="question101" > It was two days ago. <br>
<input type="radio" name="question101" > Can you help me?
</div>
</div>
<br>
<br>
<div>
8. What is your father like?
<span id="question8_answer"></span>
<div>
<input type="radio" name="question8" > He likes listenning to music.<br>
<input type="radio" name="question8" > He likes to play football. <br>
<input type="radio" name="question8" > He is friendly.<br>
<input type="radio" name="question8" > He has a car.
</div>
</div>
<br>
<br>
<button id="button1" class="button" onclick="viewScore()">Score Result</button>
<br>
<input type="text" id="grade1" value="" readonly>
<br>
<script src="testJs.js"></script>
and here is the testJs.js that i used:
var score = 0;
function viewScore() {
var answer2 = document.getElementById("question2").value;
var answer8 = document.getElementsByName("question8");
var answer101 = document.getElementsByName("question101").value;
if (answer2 == "Am") {
document.getElementById("question2_answer").style.color = "green";
document.getElementById("question2_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question2_answer").style.color = "red";
document.getElementById("question2_answer").innerHTML = "✖ Wrong!";
}
if (answer8[2].checked) {
document.getElementById("question8_answer").style.color = "green";
document.getElementById("question8_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question8_answer").style.color = "red";
document.getElementById("question8_answer").innerHTML = "✖ Wrong!";
}
if (answer101[0].checked) {
document.
getElementsById("question101_answer").style.color = "green";
document.getElementsById("question101_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementsByID("question101_answer").style.color = "red";
document.getElementsByID("question101_answer").innerHTML = "✖ Wrong!";
}
if (score<=5) {
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Elementary.";
} else if(score<=8){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Pre Intermediate.";
}else if(score<=15){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Intermediate.";
}else{
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Upper Intermediate.";
}
console.log(score);
score = 0;
}
However, I'm getting following error on question 101. I check it several times and I have no idea where does this error coming from ! It refers to question 101 and mentions cannot read property '0' of undefined.
Thanks for any help in advance.
testJs.js:26 Uncaught TypeError: Cannot read property '0' of undefined
at viewScore (testJs.js:26)
at HTMLButtonElement.onclick (testHTML.html:57)
This is happening because in this line:
var answer101 = document.getElementsByName("question101").value;
you are putting the value of the input (which is NULL or UNDEFINED because the HTMLCollection returned by getElementsByName (note the plural) doesn't have a value property) into the var answer101 and NOT the input itself.
To fix this, change the above line to:
var answer101 = document.getElementsByName("question101");
You have to select array (not value) for var answer101
var answer101 = document.getElementsByName("question101");
And correct if content for answer101
if (answer101[0].checked) {
document.getElementById("question101_answer").style.color = "green";
document.getElementById("question101_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question101_answer").style.color = "red";
document.getElementById("question101_answer").innerHTML = "✖ Wrong!";
}
I can't seem to figure out how to clear the textbox rate in my JS code from an external file and would love some help to figure out how to do it.
Can someone help me with the code and the why and how it works so that I can learn it and understand it so that I can code it effectively and efficiently?
I have included all of the original code down below.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="future_value.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<script src="future_value.js"></script>
</head>
<body>
<section>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"> </span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"> </span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</section>
</body>
</html>
JavaScript
var $ = function (id) {
return document.getElementById(id);
}
var calculateClick = function () {
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value );
var years = parseInt( $("years").value );
if (isNaN(investment) || investment < 100 || investment > 100000) {
alert("Investment must be an integer from 100 - 100,000.");
}
else if(isNaN(annualRate) || annualRate < .1 || annualRate > 12) {
alert("Annual rate must be a value from .1 - 12.");
}
else if(isNaN(years) || years < 1 || years > 50) {
alert("Years must be an integer from 1 - 50.");
}
// if all entries are valid, calulate future value
else {
futureValue = investment;
for ( i = 1; i <= years; i++ ) {
futureValue += futureValue * annualRate / 100;
}
$("future_value").value = futureValue.toFixed();
}
}
window.onload = function () {
$("calculate").onclick = calculateClick;
$("investment").focus();
}
rate = document.getElementById("rate");
rate.dblclick = "";
To add an "ondblclick" attribute to your "rate" element in JS, it world look like this:
$('rate').ondblclick = clearRate();
And then add that "clearRate()" function:
function clearRate() {
$('rate').value = ''
}
This means that when the "rate" element is double-clicked, it will trigger the function "clearRate()", which sets the value of "rate" to an empty string.
how would I remove a list item from my to do list onclick! And how would i set up a counter to add and display how many tasks i have and how many left once one is deleted.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task 1</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="script.js"></script>
</head>
<body>
<div id="container">
<h1>My To Do List</h1>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()" > Add Task</button>
</div>
<ul id="todo_list"></ul>
</body>
</html>
JavaScript
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete'>clear</button></li>";
}
}
Add an onclick event to clear button and call the function clearItem() that deletes the item.
For your second question,
And how would i set up a counter to add and display how many tasks i
have and how many left once one is deleted.
Add a variable total_added that increment when the user adds an item, and another variable remaining that decrement when the user clears an item.
var total_added = 0; //initialize the var to zero
var remaining = 0; //initialize the var to zero
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete' onclick='clearItem()'>clear</button></li>";
total_added++;
remaining++; //increment total_added and remaining when user adds an item
document.getElementById('total_added').innerHTML = "Total number of tasks added = " + total_added;
document.getElementById('remaining').innerHTML = "Number of tasks remaining = " + remaining;
}
}
function clearItem() {
event.currentTarget.parentElement.remove();
remaining--; //decrement remaining when user clears an item
document.getElementById('remaining').innerHTML = "Number of tasks remaining = " + remaining;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task 1</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="script.js"></script>
</head>
<body>
<div id="container">
<h1>My To Do List</h1>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()" > Add Task</button>
</div>
<ul id="todo_list"></ul>
<p id="total_added">Total number of tasks added = 0</p>
<p id="remaining">Number of tasks remaining = 0</p>
</body>
</html>
I think counter of the list is unnecessary. You could always count childNode in your todo_list for the left todo list. But counter for deleted list is still useful.
var list_now = document.getElementById('todo_list').childNodes.length;
Add the removeTask() function in the onClick event of the delete button and add the removeTask function.
Like this :
JS :
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
} else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete' onclick='removeTask()' >clear</button></li>";
countItems();
}
}
function removeTask() {
event.currentTarget.parentElement.remove();
countItems();
}
function countItems() {
var count = document.querySelectorAll("#todo_list > li").length;
document.getElementById("count").innerHTML = count + ' item(s)';
}
HTML :
<div id="container">
<h1 id="title">My To Do List</h1>
<p id="count"></p>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()"> Add Task</button>
</div>
<ul id="todo_list"></ul>
CodePen
Suppose I have two text fields where the user can enter any text.
One field can have: The sky is blue.
Second field have: The ocean is blue.
In Javascript what is the easiest way to check if one string entered in one field is a substring for the other field?
So far this is what I have:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Substring Test</title>
<script type="text/javascript">
function displayContent() {
var contentEntered = document.getElementById("userContent").value;
var contentEnteredSecond = document.getElementById("secondUserContent").value;
document.getElementById("result").innerHTML += "<p> The content entered was " + contentEntered + " </p>";
document.getElementById("result").innerHTML += "<p> The content entered was " + contentEnteredSecond + " </p>";
}
</script>
</head>
<body>
<h1>Substring</h1>
<div id="mainCont">
<p>Please enter any content.</p>
<p>Content:
<input type="text" id="userContent">
</p>
<p>Content:
<input type="text" id="secondUserContent">
</p>
<p>
<input type="button" onclick="displayContent();" value="Submit">
</p>
<div id="result"></div>
</div>
</body>
</html>
function checkSub(str1, str2){
if(str1.indexOf(str2) > -1 || str2.indexOf(str1) > -1) return true;
else return false;
}
In ES6 it's simple with String.prototype.includes:
str1.includes(str2) || str2.includes(str1);
You can use includes function from lodash library.
function checkSubstr(str1, str2) {
return _.includes(str1, str2) || _.includes(str2, str1);
}