Asking for user's input inside a while loop in javaScript - javascript

I'm creating a number guessing game in JavaScript. I'm using the input.value property to get user input. Now I have a while loop which should execute until the number entered by user is equal to the actual number. But I'm unable to get out of loop and ask for user input again as the while loop always evaluates to true. How can I ask for user's input again. Please suggest anything else rather than using prompt.
var correctNumber = 16
function answer() {
while (inputNumber !== correctNumber) {
var inputNumber = Number(inputValue.value)
inputNumber = Number(inputValue.value)
}
}

<html>
<body>
<label for="answer">Your guess:</label>
<input type="text" id="answer" name="answer" />
<button onclick="guessAnswer">Guess Answer</button>
<p id="feedback"></p>
<script>
const correctNumber = 16;
const feedback = document.getElementById('feedback');
function guessAnswer() {
const answer = document.getElementById('answer');
if(answer == correctNumber) {
feedback.innerHTML = 'Correct';
} else {
feedback.innerHTML = 'Incorrect';
}
}
</script>
<body>
</html>

Related

How to save texts from text box to a variable and showing the variable to append

I'm new to coding and I was wondering how to correct the following code.
Basically, I want to save the user's scanned input to a variable and display it as a prepend. Also If possible being able to scan multiple scans while it just adds it to another variable so I can export the variables. Something like this when its exported as a .txt file
testscan1
tesstscan2
ABCDEF
var string = "";
let inputStart, inputStop;
$("#scanInput")[0].onpaste = e => e.preventDefault();
// handle a key value being entered by either keyboard or scanner
var lastInput
let checkValidity = () => {
if ($("#scanInput").val().length < 8) {
$("#scanInput").val('');
} else {
$("body").append()
}
timeout = false
}
let timeout = false
$("#scanInput").keypress(function(e) {
if (performance.now() - lastInput > 50) {
$("#scanInput").val('')
}
lastInput = performance.now();
if (!timeout) {
timeout = setTimeout(checkValidity, 200)
}
});
<form autocomplete="off" onsubmit="return false">
<br>
<input type="text" name="serial" placeholder="Please scan laptop Barcode" id="scanInput" />
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

How to select two input fields at once and check if they are filled?

So I am making a game and I need to check if these two HTML <input> fields have some data before I do an alert(); saying that they won. Unfortunately, I don't know how to implement this and I have been stuck at it for hours, please do help, attaching a screenshot for assistance.
In the image, I want to constantly monitor the 2 empty <input> fields and once there is data IN BOTH, then I want to throw up an alert();
Here's what I tried:
var firstLetterField = document.querySelectorAll("input")[0].value.length;
var secondLetterField = document.querySelectorAll("input")[1].value.length;
if (!firstLetterField && !secondLetterField) {
console.log("Please ignore this message: NOT_FILLED...");
} else {
alert("That's right! The word was " + spellingOfWord.join("").toUpperCase() + "! Thanks for playing!");
window.location.href = "/";
}
How about just adding a common class to your user input and use querySelectorAll to perform your check ?
eg
<html>
<body id="game">
<input data-expected="m" class="user-input" />
<input data-expected="a" class="user-input" />
<div id="keyboard">
<button>d</button>
<button>c</button>
<button>b</button>
<button>a</button>
<button>d</button>
<button>m</button>
<button>e</button>
</div>
</body>
<script>
const inputs = document.querySelectorAll(".user-input");
const keyboard = document
.querySelector("#keyboard")
.querySelectorAll("button");
let inputPosition = 0;
function nextInput() {
inputPosition += 1;
if (inputPosition === inputs.length) {
alert("you won");
}
}
function handleClick(event) {
const input = inputs.item(inputPosition);
const submittedValue = event.target.innerHTML;
if (input.dataset.expected === submittedValue) {
input.value = submittedValue;
setTimeout(nextInput);
}
}
keyboard.forEach((button) => button.addEventListener("click", handleClick));
</script>
</html>
You could register an event-listener and check if your condition is met:
var firstLetterField = document.querySelectorAll("input")[0];
var secondLetterField = document.querySelectorAll("input")[1];
// Function to call when both inputs contain values
function bothReady() {
console.log("bothReady", firstLetterField.value, secondLetterField.value);
}
document.addEventListener("keyup", function (e) {
// Wait for both fields to have values
if (firstLetterField.value.length > 0 && secondLetterField.value.length > 0) {
bothReady();
}
});
Your code just works fine. There were just some mistakes that I noticed.
You tried to use the length to detect if it is empty. You could instead compare it with an empty string.
You reversed the boolean value using else. It looks that does the opposite of what you want.
In the code you showed you didn't actually defined spellingOfWord. So I did it for you.
The location "/" is not compatible in every server. So I would recomment replacing it by "index.html".
Here is the code that I just created
function input_inputEvent() {
var firstLetterField = document.querySelectorAll("input")[0].value;
var secondLetterField = document.querySelectorAll("input")[1].value;
var thirdLetterField = document.querySelectorAll("input")[2].value;
if (firstLetterField.length != "" && secondLetterField != "") {
alert(
"That's right! The word was " +
[firstLetterField,secondLetterField,thirdLetterField].join("").toUpperCase() +
"! Thanks for playing!"
);
window.location.href = "index.html";
}
}

Showing an image based on a number range in Javascript

I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.
Below is the javascript I am using:
function start()
{
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent()
{
let number = document.getElementById('number');
let liquid = document.getElementById('Bar');
if parseInt(number <= 20)
{
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
}
else if (number >= 21)
{
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
else if (isNaN(number) || number < 0)
{
alert("Invalid Entry. Enter a Number.")
}
}
window.onload = start;
Here is the HTML code that goes with it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ID Check?</title>
<script src="scripts/pt2script.js"></script>
</head>
<body>
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" value="Enter a number...">
<button onclick="toggleContent()" id="button1">Submit</button>
</body>
</html>
You need to get the value from input and convert it to a number by using an unary plus +.
function start() {
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent() {
let number = +document.getElementById('number').value; // take value as a number
let liquid = document.getElementById('Bar');
if (isNaN(number) || number < 0) { // move exit condition to top and exit early
alert("Invalid Entry. Enter a Number.")
return;
}
if (number <= 20) { // condition without parseint
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
} else { // no need for another check
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
}
window.onload = start;
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:
$('.btn').on('click', function() {
let val = $('#num').val();
val = parseInt(val);
if(val >= 21) {
$('img').attr('src', '/path-to-soda');
}
else {
$('img').attr('src', '/other-path');
}
});
As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.

Addition to a variable reaches condition border, yet conditionied behavior doesn't take place

The purpose of the following script is to count the number of tries a user answered wrong (filled in a wrong password as value). After the "tries" variable went from 0 to 2, the error variable becomes 1 and the user is moved out from the form's webpage.
I tried to use conditionals to establish a flow of that process but these seem to fail in the sense that wrong password won't get the user out of the site and the correct password isn't recognized.
I seem to have a logical mistake I might lack some knowledge to find for now and it feels sour.
As a beginner I ask, what's wrong in the conditional system?
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
document.querySelector("#myButton").onclick = function() {
let tries = 0;
let error = 0;
let password = 'tiesto';
let passwordValue = document.querySelector("#user").value;
if (passwordValue === password) {
document.location = 'http://www.maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 2) {
error++;
}
if (error === 1) {
document.location = 'http://www.microsoft.com';
}
};
</script>
</body>
</html>
In the function you are intializing tries to 0, so it becomes 0 each time the function is called and after increment becomes 1, and it never reaches 2 you can declare tries outside the function, something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
document.querySelector("#myButton").onclick = function() {
let error = 0;
let password = 'tiesto';
let passwordValue = document.querySelector("#user").value;
if (passwordValue === password) {
document.location = 'http://www.maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 2) {
error++;
}
if (error === 1) {
document.location = 'http://www.microsoft.com';
}
};
</script>
</body>
</html>
You put let tries = 0; in the onclick funtion, so it will be set to 0 everytime, never reach 2, so just move it out of the function.
let tries = 0;
document.querySelector("#myButton").onclick = function() {
let error = 0;
let password = 'tiesto';
Thanks to Dij, and Evelyn Ma, I now understand my mistake.
I didn't realize invoking a function on an event (such as onload) necessites taking all variables set to 0 or a string out of the function so these won't be changed by function execution:
Each time the event is triggered and the function executed, the values will be resetted if declared inside the function so the level set in the condition will never be reached.
For example: When var tries set to 0 outside the function, the user could try up until, say, 3 tries and in each execution the var won't be resetted but if it's inside the function it will go back from 1 to 0 each try.
I also had 2 other unrelated mistakes in the code:
besides moving all variables set to 0 or a string outside, I had to include the querySelector inside to check it's value each time anew.
I didn't use return, and in a specific correct way.
Note: Passwords shouldn't be on the code but be called from Database, but this is just an exercise.
Here's the full working exercise code:
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
Enter password to continue: <br>
<input type="text" id="passwordInput"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordInput = document.querySelector('#passwordInput').value;
if (password === passwordInput) {
return window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>

How to take an input that is equal to 10 and perform a function that says awesome to the screen

I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.
<!DOCTYPE html>
<html>
<head>
<title>Fizzbuzz Input Field</title>
<script src="scripts.js"></script>
</head>
<body>
<form>
<input type="number" id="userInput"></input>
<button onclick="fizzBuzz()">Go</button>
</form>
</body>
</html>
window.onload = function() {
alert("Page is loaded");
};
var fizzBuzz = function() {
var userInput = document.getElementById("userInput");
fizzBuzz.onclick = function() {
if(userInput.value == 10) {
document.write("awesome");
};
};
}
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.
var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
if (input.value === '10') {
button.after("awesome");
}
})
<input type="number" id="userInput">
<button>Go</button>
I think what you are looking for is eval before using it, you should search the web for why eval is evil.
What you want is something like this:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
// First we get the numeric value written to the input (or NaN if it's not a number)
var inputValue = parseInt(document.getElementById('userInput').value, 10);
// Define the element to which write the text (you usually want a DIV for this)
var outputElement = document.getElementById('outputDiv');
if ( ! isNaN(inputValue) ) {
outputElement.innerHTML = "awesome!";
}
else {
// The value is not a number, so just clean the result
outputElement.innerHTML = "";
}
});
Of course, for this to work, you should have at least:
<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.
<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
alert('Number is not equal to ten!');
}else {
alert('awesome');
}
}
</script>
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.
var userInput = document.getElementById('userInput');
userInput.oninput = function() {
if( this.value == 10 ) alert('awesome');
}

Categories

Resources