Please help me understand why my code is not reacting how I’d expect it to?
So I’m iterating over the list of values in the for loop, then if they match the value that was submitted by the form, it should return that value, and if it doesnt match, it should return -1. If I leave out the ‘else’ statement in the if condition, it works (obviously without returning -1 if there is no value matched). But with the else, it will only return the first value if its been entered (10 in this case), otherwise it will always return -1. (like if I enter 20, it will return -1, even though its in my values list)
What am I missing/not understanding here?
// reference the form
var myForm = document.getElementById('findValue');
// our list of random values
var values = [10,20,30,40,50,60,70,80,90,100,234,255,345,366,900,1000,1002,1025,2034];
// on form submit
myForm.onsubmit = function(evt) {
var valueToFind = document.getElementById('myValue').value;
// do not let it refresh the page/send a query
evt.preventDefault();
for(var i = 0; i < values.length; i++) {
if(valueToFind == values[i]) {
alert(values[i]);
}
else {
alert(-1);
return false;
}
}
};
Thank you so much!
You’re not letting it search to the end. The first time there’s no match, it returns.
You should be alerting as soon as a match is found, and returning
trueto allow the submission. If no match, then returnfalseafter the loop.EDIT: Your question uses the work
returnwhen I think you mean something else.