functions not running in the right order - javascript

in my while loop I was hoping it will keep prompting the user for entry unless I break out of the loop. However, once I get into my if block it wont to peform printToScreen(message) function unless I terminate the code.
Not sure what I am doing wrong here. I am expecting it to print message before continuing to prompt.
how can I fix this?
let message;
let search;
function printToScreen(message){
let outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function promptUser (){
search = prompt("Enter student name");
return search;
}
function searchStudent(){
while(true){
search =promptUser();
for(let i = 0; i<students.length; i++){
if(search.toLowerCase() === students[i].name.toLowerCase())
{
let student = students[i];
message = `<h4>Student: ${student.name}</h4>`;
message += `<p> Track: ${student.track}
<br> Achievements:${student.achievements}
<br> Points: ${student.points}
</p>`;
printToScreen(message);
}
else if( search ===null || search.toLowerCase() === 'quit'){
message = `<p>Thanks.Goodbye! </p>`;
printToScreen(message);
break;
}
else{
message = `<p> Student ${search} does not exist. Try Again!</p>`;
printToScreen(message);
}
}
}
}
searchStudent();

That's because the browser won't redraw the page while it is still computing some js.
What you could do is replace your while(true) by a recursive call in a setTimeout:
function searchStudent(){
search =promptUser();
for(let i = 0; i<students.length; i++){
if(search.toLowerCase() === students[i].name.toLowerCase())
{
let student = students[i];
message = `<h4>Student: ${student.name}</h4>`;
message += `<p> Track: ${student.track}
<br> Achievements:${student.achievements}
<br> Points: ${student.points}
</p>`;
printToScreen(message);
}
else if( search ===null || search.toLowerCase() === 'quit'){
message = `<p>Thanks.Goodbye! </p>`;
printToScreen(message);
break;
}
else{
message = `<p> Student ${search} does not exist. Try Again!</p>`;
printToScreen(message);
}
}
setTimeout(function(){
searchStudent();
},5);
}
searchStudent();

Related

How can I limit the number of password attempts in a simple form?

I'm trying to make a basic password checker with 3 attempts using a textbox and button. So in the HTML I have these two elements and a paragraph in which I want to post the answer (correct, wrong, out of entries).
This is the HTML code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="description" content="Test page for Java.">
<link rel="stylesheet" href="style.css">
<title>Java Tester</title>
</head>
<body>
<input id="textbox" type="text">
<button id="button">Enter</button>
<p id="answer"></p>
<script src="script.js"></script>
</body>
</html>
I am using a while loop for the attempts in JavaScript. I understand that the following code does not work, as entering the wrong answer the first time loops three times and goes straight to "out of entries". I'm trying to figure out how to write this, so I have three attempts.
JavaScript code:
var answer = document.getElementById("answer");
var textbox = document.getElementById("textbox");
var button = document.getElementById("button");
var password = "wordpass";
var response;
var entryCount = 0;
var entryLimit = 3;
var error = false;
button.addEventListener("click", function(){
while(textbox.value != password && !error){
if(entryCount < entryLimit){
answer.innerHTML = "Wrong Password";
entryCount++;
textbox.value = "";
} else{
error = true;
}
}
if(error){
answer.innerHTML = "Out of entries";
} else{
answer.innerHTML = "Correct Password";
}
However, I figured if I just write some random text in the while loop just under textbox.value=""; it starts working the way I want it to - I can input the pass 3 times. Why is this? Just for clearance here is the JS code that works.
Working JS code:
var answer = document.getElementById("answer");
var textbox = document.getElementById("textbox");
var button = document.getElementById("button");
var password = "wordpass";
var response;
var entryCount = 0;
var entryLimit = 3;
var error = false;
button.addEventListener("click", function(){
while(textbox.value != password && !error){
if(entryCount < entryLimit){
answer.innerHTML = "Wrong Password";
entryCount++;
textbox.value = "";
ousdgohjrandomfoihsodfhsdfhsdofihoihsoidhsdoufhouhsdfrduiiugsdf
} else{
error = true;
}
}
if(error){
answer.innerHTML = "Out of entries";
} else{
answer.innerHTML = "Correct Password";
}
});
It is not working the first time because the while loop is unnecessary. It is looping over the same answer until errorcount is exceeded. When you add the random text, it throws an runtime error and breaks the loop in the first run. Replacing the while with a simple if should work.
The code reacting to the click event doesn't "pause" and wait for UI input again, so the while loop isn't really necessary. You could replace it with an if-check, and then reset the retry count on success. You can also drop the error variable and move the answer responses in its place.
I've also changed the logic a bit to check the retry count as the first check; otherwise the user would be able to continue to guess even if they exceed the retry count.
var answer = document.getElementById("answer");
var textbox = document.getElementById("textbox");
var button = document.getElementById("button");
var password = "wordpass";
var entryCount = 0;
var entryLimit = 3;
button.addEventListener("click", function(){
if (entryCount < entryLimit) {
if (textbox.value != password){
answer.innerHTML = "Wrong Password";
entryCount++;
textbox.value = "";
} else {
// success!
entryCount = 0;
answer.innerHTML = "Correct Password";
}
} else {
answer.innerHTML = "Out of entries";
}
}
Here's a working example:
var answer = document.getElementById("answer");
var textbox = document.getElementById("textbox");
var button = document.getElementById("button");
var password = "wordpass";
var entryCount = 0;
var entryLimit = 3;
button.addEventListener("click", function(){
if (entryCount < entryLimit) {
if (textbox.value != password){
answer.innerHTML = "Wrong Password";
entryCount++;
textbox.value = "";
} else {
// success!
entryCount = 0;
answer.innerHTML = "Correct Password";
}
} else {
answer.innerHTML = "Out of entries";
}
});
<input type="text" id="textbox" placeholder="Password" />
<button id="button" type="button">Login</button>
<div id="answer"></div>

Switch Statement - Multiple results for single case

I have this page:
var count = 0;
function switchStatement() {
var text;
var answers = document.getElementById("userInput").value;
switch (answers) {
case "":
text = (count > 0) ? "You didn't type anything." : "Please type something down...";
if (count < 1)
count++;
else
count = 0;
break;
default:
text = "Good job!";
}
document.getElementById("feedback").innerHTML = text;
document.getElementById("userInput").value = "";
}
<p>Please write something down and press "enter".</p>
<input id="userInput" type="text" onKeyDown="if(event.keyCode==13) switchStatement();">
<p id="feedback"></p>
When the user doesn't type anything before pressing "enter", (that's case = "";), a message will show up. If he does the same thing again, a different message will show up. If he does it a third time, it will loop back to the first message.
How can I add more messages to avoid having such a small loop? Say, if I wanted to have 5 different messages for when the user doesn't type anything, what should I change in my code?
You could use an array of messages :
var messages = ["message 1...", "message 2...", "message 3...", "message 4...", "message 5..."]
Then use the count variable as the index of this array to show the messages one after other.
NOTE: You must init the count to the default value 0 in case the user typed something so the next empty submit will show the first message in index 0.
var count = 0;
var messages = ["message 1...", "message 2...", "message 3...", "message 4...", "message 5..."];
function switchStatement() {
var text;
var answers = document.getElementById("userInput").value;
switch (answers) {
case "":
text = messages[count];
count = count < messages.length - 1 ? count + 1 : 0;
break;
default:
text = "Good job!";
count = 0;
}
document.getElementById("feedback").innerHTML = text;
document.getElementById("userInput").value = "";
}
<p>Please write something down and press "enter".</p>
<input id="userInput" type="text" onKeyDown="if(event.keyCode==13) switchStatement();">
<p id="feedback"></p>

Why my else condition is beeing executed?

I am new to Javascript and I was making a little chat bot, nothing to fancy, but I am stuck in a problem where if I input something to it that matches a value inside an array it will execute the if and the else condition.
function readInput(){
var words = ["hello", "hi", "holis", "holus"];
var userInput = document.getElementById("userInput").value.toLowerCase();
console.log(" Users says: " + userInput);
for(var i = 0; i < words.length; i++){
if(userInput == words[i]){
console.log("bot says: " + "hi!");
}else {
console.log("bot says " + "i dont understand");
}
}
//clean user input
var clearInput = document.getElementById("userInput").value="";
}
<input type="text" id="userInput" value="">
<button type="button" name="button" onclick="readInput()">Say</button>
Any help will be appreciated
Modify your for statement.
Define a variable to check if your script know the word. In the for statement, if the input word is in the words, then set the variable true then break. Finally if the check variable is false, than say I don't understand:
var check = false
for (var i = 0; i < words.length; i++) {
if (userInput == words[i]) {
console.log("bot says: " + "hi!");
check = true;
break
}
}
if (!check) {
console.log("bot says " + "i dont understand");
}

JavaScript checking an array of objects is coming up false when it should be true

Working on a pseudo login form and ran into a problem with the if-else statement. I created a function to check an array of objects when submitted and see if they match the text inside the input. The last else statement is supposed to print only if the email input is not found. I discovered taking out the last else statement fixed the issue, but made it impossible to print 'user not found' if there were no matches. Pretty sure it's a simple fix but I cannot seem to find what is wrong.
How do I get this to run properly without deleting that last else statement? (Included the HTML for reference.)
var logForm = document.querySelector("#logForm");
var output = document.querySelector("#output");
var users = [{
email: "email1#address.com",
password: "123"
}, {
email: "email2#address.com",
password: "123again"
}, {
email: "email3#address.com",
password: "123again2"
}];
var submitHandler = function(e) {
e.preventDefault();
output.innerText = '';
var inputEmail = logForm.email.value;
var inputPassword = logForm.password.value;
console.log(inputEmail);
console.log(inputPassword);
for (var i = 0; i < users.length; i++) {
if (inputEmail === users[i].email) {
if (inputPassword === users[i].password) {
output.innerHTML = "Successfully logged in as " + users[i].email;
} else {
output.innerHTML = "Invaild password.";
}
} else {
output.innerHTML = "User not found.";
}
}
};
logForm.addEventListener('submit', submitHandler);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Form</title>
</head>
<body>
<p>
<form id="logForm">
<input type="text" name="email" placeholder="E-mail"></input>
<input type="text" name="password" placeholder="Password"></input>
<button type="submit">Log In</button>
</form>
</p>
<p id="output"></p>
</body>
</html>
You need to stop search once user is found in the array. To do so you need to break the loop or simply return from the function:
for (var i = 0; i < users.length; i++) {
if (inputEmail === users[i].email) {
if (inputPassword === users[i].password) {
output.innerHTML = "Successfully logged in as " + users[i].email;
} else {
output.innerHTML = "Invaild password.";
}
break;
} else {
output.innerHTML = "User not found.";
}
}
Demo: http://jsfiddle.net/5mfaoz9e/1/
Three things to fix your problem:
Declare a boolean variable let's say userFound and set it to true if the email input is found inside the for loop.
Use break statement at the end of if (inputEmail === users[i].email) block to stop the for loop once the email input is found.
Move output.innerHTML = "User not found." outside of the for loop and only execute that statement if userFound equals false.
Below is the modified code
var userFound = false;
for (var i = 0; i < users.length; i++) {
if (inputEmail === users[i].email) {
if (inputPassword === users[i].password) {
output.innerHTML = "Successfully logged in as " + users[i].email;
} else {
output.innerHTML = "Invalid password.";
}
userFound = true;
break; // stop the iteration
}
}
if (!userFound) {
output.innerHTML = "User not found."; // only do this if user isn't found
}
Demo: http://jsfiddle.net/rjdxxvmk/

How to Get Input Field Value JavaScript

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
}
}

Categories