Why my else condition is beeing executed? - javascript

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");
}

Related

functions not running in the right order

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();

check if word already exists in the array [duplicate]

This question already has answers here:
Check if string inside an array javascript
(2 answers)
Closed 5 years ago.
I'm trying to check if the inputted word is already inside of my array. SO for example, if someone enters 'cat' more than once an error message will display saying "cat has already been entered". I've tried a few different combinations of code but nothing I do seems to work. The findword function is what I have so far. Can someone take a look at my code and explain why its not working and provide a possible fix.
On another note, why doesn't the "word: empty" message pop up when the input field has been left blank?.
<body>
<input type="text" id=input></input>
<button onclick="addword()" class="button" type = "button">Add word</button><br><br>
<button onclick="start()" class="button" type = "button">Process word</button><br><br>
<p id="ErrorOutput"></p>
<p id="output"></p>
<p id="nameExists"></p>
</body>
.
var array = [];
return = document.getElementById("input").value;
function start() {
var word = "word List";
var i = array.length
if (word.trim() === "") {
word = "word: Empty"
}
document.getElementById('ErrorOutput').innerHTML = word
while (i--) {
document.getElementById('output').innerHTML = array[i] + "<br/>" + document.getElementById('output').innerHTML;
}
var longestWord = {
longword: '',len: 0};
array.forEach(w => {
if (longestWord.len < w.length) {
longestWord.text = w;
longestWord.len = w.length;
}
});
document.getElementById('ErrorOutput').innerHTML = "The longest name in the array is " + longestWord.len + " characters";
}
function addword() {
return = document.getElementById('input').value;
array.push(return);
}
function findword() {
var nameExists = array.indexOf(
return) < 0 ?
'The number ' +
return +' does not exist in the array': 'The number ' +
return +' exists in the array'
document.getElementById('nameExists').textContent = nameExists
}
You can use array.indexOf(word) (command for your situation) to find the position of the word.
If the position is -1 the word is not inside the array.
More information on W3

How to find if there is a space in a string... tricky

I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}

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/

Check if Number entered is correct By ID - JavaScript

Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}
See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →
Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}

Categories