I am trying to make some kind of search function, where a pop-up would appear and ask for an input from the customer and then compare it to the array items and return another alert window with either "found" or "not found"
Here is my code for the specific function:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.prompt("found");
} else {
window.prompt("not found");
}
}
}
It is kind of working. The problem is that it keeps showing a new alert window for every single element in the array. For example if I have 6 elements in the array and only one is matching the search input, then it will show me 5 alert windows with "not found" and one with "found". Another one appears after i close the previous one or if I click the ok button. How do I make it show me the alert window only once to tell me if it found it or not? Thanks!
Put the alert (not prompt) after the loop. Also need to switch to using a variable to track whether or not the item was found:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
break;
}
}
window.alert(found ? 'found' : 'not found');
}
Instead of showing the alert every time, set a variable such as var found=true. After loop terminates then show alert based on status of that var.
To show alert only once you have to execute the alert after loop ends, not inside loop.
Since you aren't doing anything else in your function after the loop, you can simply return when you find the element you were looking for. And only display the "not found" if you finish the loop without finding the element.
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.alert("found");
return;
}
}
window.alert("not found");
}
You could also simplify this by using Array.prototype.indexOf or Array.prototype.includes
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
}
}
if(found == true)
window.prompt("found");
else
window.prompt("not found")
}
you are telling it to show the message every time it finds one, if you are seeking to finding only 1 match then just terminate the loop when you find it.
End the loop using break; or simply just set i to the arrays length:
......
if (model.items[i] == searchInput) {
window.prompt("found");
return 0;
}
.....
window.prompt("Not found"); //if fucntion doesn't return then it's not found.
OR
var found = false;
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
break;
}
.....
if(!found) window.prompt("Not found");
OR
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
i = items.length;
}
.....
if(!found) window.prompt("Not found");
Related
I want to redirect a user to a new page if their login details are correct. However, when I use the window.location.href("portal.html") in a simple if statement to check if user details match an already stored data in a variable, it works, but when I use it in a for loop to loop through an array of stored data it doesn't render the the portal.html page.
please help, Thanks.
for(let i = 0; i<= objPeople.length; i++){
if(name === objPeople[i].username && pass === objPeople[i].password){
window.location.href="portal.html"
return
}
} console.log("incorrect login details");
Use find instead of a for loop:
if (objPeople.find(x => x.username === name && x.password === pass))
window.location.href="portal.html"
else
console.log("incorrect login details")
I tested your code and like Adnan Ahmed mentioned it does not work because of the return statement. It should be break.
Try it like this
let matches = false;
for(let i = 0; i<= objPeople.length; i++){
if(name === objPeople[i].username && pass === objPeople[i].password){
matches = true;
}
}
if(matches){
window.location.href="portal.html"
}
Just remove return. return statement prevents the redirection to the new page. I tried following example and it works:
for (let i = 0; i < 20; i++) {
if (i === 10)
window.location.href = "https://google.com";
}
I am new to javascript and struggling with the use of arrays.
I am trying to check if user input value is in an array I declared called fruits. If it is I want to execute code. If it is not I want an alert displayed. I tried using the
instanceof
method to check the value but the code doesn't execute any of the if else statement. Any ideas as to why?
$("#submit-btn").bind("click", function() {
var comment = $("#comments");
var commentValue = $.trim(comment.val());
var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += fruits[index];
if (commentValue.length === 0) {
alert('Comments are required to continue!');
}
else if (commentValue instanceof fruits){
execute code
});
}
else {
alert('not a valid fruit');
}
return false;
}
});
Your first if should be outside the for loop.
Inside you simply change the else if to
if(commentValue === fruits[index])
And then you move the code inside the else out after the for loop.
A simpler way of doing it would be:
if (commentValue.length === 0) {
alert('Comments are required to continue!');
return false;
}
if(fruits.indexOf(commentValue) > -1) {
execute code
return false;
}
alert('not a valid fruit');
return false;
Try indexOf(), if indexOf return anything bigger then -1, you have match
like this:
else if (commentValue.indexOf(fruits[index]) > -1){
So, I want to check wether the input that I give is being correctly executed, but why does the if statement always return false even i give the correct input?
I don't want the solution only the need explanation. Please is there anyone who could explain? I've included my html input elements Just in case something wrong with it.
<script>
var text1 = ["O","K","E"];
var text2 = ["_","_","_"];
function guess(j){
for(i=0; i < text1.length; i++){
if(j == text1[i]){
text2[i] = j;
console.log(text2[i])
}
else {
console.log("try again")
}
}
}
</script>
The comment of #Unglückspilz in code:
// extra "K" to show how to handle multiple finds
var text1 = ["O","K","E","K"];
var text2 = ["_","_","_","_"];
function guess(j){
// a flag to set if one or more letters were found
found = false;
// check every letter in the haystack against given needle
for(i=0; i < text1.length; i++){
if(j == text1[i]){
// exchange underbar against found letter(s)
text2[i] = j;
console.log(text2[i]);
// set flag to true
found = true;
}
}
// no letter was correct
if(!found){
console.log("try again");
}
// return boolean if anything was found (but not how many)
return found;
}
I was stuck trying to validate if a radiobutton was selected or not and, in consequence, show alerts. Well, I found the mistake (I was putting the conditional statement inside the loop).
Even I solved the problem, I can’t figure out yet why my code works correctly outside the loop but doesn’t work inside it. Now I'm stuck with this.
I appreciate if anyone can tell me what’s the reason.
Below you'll see both JS codes, but here you have the fiddles examples:
JSFiddle that doesn't work
JSFiddle that works
This is the JS code that doesn’t work:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
result = true;
break;
}
if(result === false){
alert('Please, choose an option');
return false;
}else{
alert('You\'ve choosen ' + getNames[i].value)
}
}//Loop ends here.
}
And this is the JS code that works without problems:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
result = true;
break;
}
}//Loop ends here.
if(result === false){
alert('Please, choose an option');
return false;
}else{
alert('You\'ve choosen ' + getNames[i].value)
}
}
Maybe the for loop in JS code that doesn’t work has a wrong logic, it means that if the first radiobutton checked, the for loop stops; if the first radiobutton does not checked, it will alert 'Please, choose an option' and stops the for loop. The logic only validates the first radiobutton. Maybe thats the problem.
It's because of your break; line.
When it's inside the loop you're breaking it out on true before it has a chance to hit the following code: if(result === false)
break is breaking out of the entire loop which means it never hit's your if(result===false)
Hope that helps!
Wrong logic inside the loop, try this:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
alert('You\'ve chosen ' + getNames[i].value)
result = true
}
if (i == getNames.length - 1 && !result)
{
alert('Please, choose an option')
}
}
}
If your question is how do I make it work, there are several good suggestions in the answers.
If you want to know: "Why didn't it work using the first method?" The best answer is that the break; line was causing your loop to terminate immediately, and therefore preventing the alert("You've chosen...") from having the opportunity to trigger.
I followed the advice from a previous question to get my promps to add values to an array, but it has caused my program to throw up True values when they are not.
HIGHEST_GRADE = 7;
LOWEST_GRADE = 0;
var course = new Array();
var grade = new Array();
while(confirm("Would you like to add a course?")){
course.push( prompt("Enter the course code. Example - ABC1234") );
};
var upperTest = course.slice(0,3);
var integerTest = course.slice(4,7);
if (course.length !== 7) {
alert ('Invalid Course Code');
}
if (upperTest !== upperTest.toUpperCase()) {
alert ('Invalid Course Code');
}
if (isNaN(integerTest)) {
alert('Invalid Course Code');
}
if (isNaN(grade)) {
alert('Invalid Grade');
}
if (LOWEST_GRADE > grade || HIGHEST_GRADE < grade) {
alert('Invalid Grade');
}
I have it set to make sure the entered text matches the conditions, but since the .push was added the whole thing stuffs up.
I get an Invalid Course Code error, something is playing up with that.
The Array is used to store multiple courses, which is fine. But, since it's an array, you need to access each position of it to validate each individual course, using a loop:
var courses = new Array(); // use the name courses instead, to indicate that it's a collection
for (var i = 0; i < courses.length; i++) {
var course = courses[i];
var upperTest = course.slice(0,3);
var integerTest = course.slice(4,7);
if (course.length !== 7) {
alert ('Invalid Course Code');
}
if (upperTest !== upperTest.toUpperCase()) {
alert ('Invalid Course Code');
}
if (isNaN(integerTest)) {
alert('Invalid Course Code');
}
}
This will validate every course that is in the Array. Otherwise, when you test courses.length, you'll be validating the number of elements in the array, not the number of characters of each course.
The same needs to be done for the grades array.
Do you want to validate entered course code? In such case you need to do it with the item not with the whole array:
while (confirm("...")) {
var courseCode = prompt("...");
var upperTest = course.slice(0,3);
var integerTest = course.slice(4,7);
if (courseCode.length !== 7) {
alert ('Invalid Course Code');
continue;
}
// place your other if's here
courses.push(courseCode);
}