0

In the code below I have a form input. When the user searches for a string that happens to be in the array I want it to output the query. When a user happens to search for a string not in the array I want to output an error message. The problem is when a user searches for a string that is other than item [0] in the array (in this case ipsum) they get an error message and then they get their query returned. I want to know if this can be remedied using the code below or if a different methodology for doing this should be pursued ( I know that's an opinion ).

<form>
<input type="text" id="formInput"></input>
<input type = "button" id="search"></input>

</form>


<script>


var search = document.getElementById("search");


var data = ["lorim", "ipsum"];

search.onclick = function(){
var formInput = document.getElementById("formInput").value;
for (i=0; i<data.length; i++){

    if (data[i] === formInput) {

      alert(data[i]);
    }   
      else{ alert("not working yet");   }
}
};

</script>

2 Answers 2

1

you don't need a loop, just use indexOf:

search.onclick = function(){
    var formInput = document.getElementById("formInput").value;

    if (data.indexOf(formInput) === -1) {
        // they entered a bad search term
        return;
    }

    // do the rest of your search logic
};
Sign up to request clarification or add additional context in comments.

Comments

1

:) Keep at it.

The thing to remember is that you can only say 'nope didn't find it' after searching everything. So... keep a flag :)

var didntFind = true;
for (var i = 0; i < data.length; i++) {
    if (data[i] === formInput) {
        alert(data[i]);
        didntFind = false;
        break;
    }
}

if (didntFind) alert('error!');

You can also check if i === data.length-1 after the loop, but the above code should be less confusing for you. Hope this helps

1 Comment

Thanks for this. The other answer was easier and more to the point but I appreciate this regardless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.