1

What I am attempting to do in the code below is to create a search form whereby when the search input matches any of the array elements an alert pops up.As of right now it doesn't work. I think the problem is I'm not sure how to write out the logic in the first line of the if statement.

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

</form>


<script>


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

var data = ["yay"];

search.onclick = function(){

for (i=0; i<data.length; i++){

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



</script>
2
  • 1
    Can you explain what "doesn't work" means? Does it alert you at all? Does it give you an error? Commented Oct 4, 2012 at 19:57
  • When I input "yay" into the search box the result is "not working". The result should be "yay" as a result of the input matching the array element. I might not actually need a for-loop to do this but I am doing this to learn so I am doing certain tasks multiple ways. Commented Oct 4, 2012 at 20:00

1 Answer 1

1

Move the line where you get the input into the onclick function:

<form>
 <input type="text" id="formInput"></input>
 <input type="button" id="search"></input>
</form>
<script>
 var search = document.getElementById("search");
 var data = ["yay"];

 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>

Currently, it is only reading the form input once, when the page loads (before the user has a chance to enter anything). If you put that line inside the onclick function, then it checks the input just before it searches the array.

Sign up to request clarification or add additional context in comments.

Comments

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.