Robert Kraaijeveld
Robert Kraaijeveld

Reputation: 695

JavaScript: How do I compare user input to an array?

I have been trying to make a very simple search engine for a school project, but I can't figure out how to compare the user input I receive (a string from an input-textbox) to data I have in an array (A NodeList object with a bunch of names).

I will elaborate a little bit on exactly what I want to achieve: I have a HTML page which contains a input form and a bunch of movie titles (in format) and I want to compare what the user types in the input form to the movie titles that are on the page. If the user input matches one of the movie titles I want that movies' highlighted, and if the input doesn't match any movies, I just want an alert box to pop up saying that the input didn't match any movies.

I have been trying to do it like this:

var All_Titles = document.getElementsByTagName("h3");
var User_Input = document.forms["search_form"];

function InputValidation() {
    var x = document.forms["search_form"]["input_box"].value;

    if (x == "" || x == null) {
        alert("You haven't entered anything");
    } else {
        Search();
    }
}

function Search() {
    if (User_Input == All_Titles) {
        document.writeln("It worked!");
    } else {
        alert("No matched movies");
    }
}

As you can see, I first capture the user input in a var called "User_Input", and I do the same with the movie titles.

Then, I check if the user has actually any text into the search form; if they didn't, they receive an error message and if they did, I run the Search() function, which is defined below.

Here comes the tricky part: I don't really know how I can compare the user input to the 's that I have! I have tried it with an If-Statement as you can see, but that doesn't seem to work.

Can anyone assist me with this problem?

Upvotes: 1

Views: 11972

Answers (5)

eitank
eitank

Reputation: 330

I prefer using jQuery witch allows to do the same with less coding.

using jQuery:

<script type="text/javascript">
function search() {
    var flag = false;
    movieName = $("#movieSearch").val();
    $(".moviesList").children("h3").each(function(index) {
        if (movieName === $(this).html()) {
            $(this).css("background-color", "yellow");
            flag = true;
        } else {
            $(this).css("background-color", "white");
        }
    });
    if(flag == false) {
        alert("no such movie was found");
    }
}
</script>

same code but only JS (less readable and maintainable):

<script type="text/javascript">
function search() {
    var flag = false;
    movieName = document.getElementById("movieSearch").value;
    movies = document.getElementsByTagName("h3");
    for (var i = 0; i < movies.length; i++) {
        if (movieName === movies[i].innerHTML) {
            movies[i].style.backgroundColor = "yellow";
            flag = true;
        } else {
            movies[i].style.backgroundColor = "white";
        }
    }
    if(flag == false) {
        alert("no such movie was found");
    }
}
</script>

HTML:

<div class="moviesList">
    <h3>HHH</h3>
    <h3>mmm</h3>
    <h3>123</h3>
</div>    
<input type="text" id="movieSearch" />
<button onclick="search()">Search By Name</button>

jQuery is a very common js library. use it by simply adding: <script src="http://code.jquery.com/jquery-latest.min.js"></script>

Upvotes: 5

user2575725
user2575725

Reputation:

You may try this example

var search = function() {
  var movie = document.getElementById("movie").value;
  if(!movie.replace(/\s+/g,'')) {//remove blank spaces
    alert('Movie name required !');
    return;
  }
  movie = movie.toUpperCase();
  var list = document.getElementById('movieList');
  list = list.getElementsByTagName('li');//movie title list
  var i = list.length, html, flag = false, matches = [];
  while(i --) {//walk through the list
    html = list[i].innerHTML.toUpperCase();//get the movie in the li
    if(-1 !== html.indexOf(movie)){//-1, string not found
      flag = true;
      matches.push(html);
    }
  }
  if(!flag) {
    alert('No match found !');
  } else {
    alert('Matched: ' + matches.join(', '));//show matching movies csv
  }
};
<ul id="movieList">
  <li>Star Wars</li>
  <li>X-Men</li>
  <li>MIB</li>
</ul>

<p>
  Search <input type="text" id="movie"/><input type="button" onclick="search()" value="Search"/>
</p>

Upvotes: 1

Mahesh
Mahesh

Reputation: 1081

This solution may work for you.. try it

  var arr = [];
    for (var i = 0, ref = arr.length = All_Titles.length; i < ref; i++) {
     arr[i] = All_Titles[i];
    } 

   function Search()
    {

        if (arr.indexOf(User_Input)>-1)
        {
            alert("yes");
        }
        else
        {
            alert("not");
        }

    } 


  Array.prototype.indexOf = function(elt)
    {
        var len = this.length >>> 0;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
                ? Math.ceil(from)
                : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++)
        {
            if (from in this &&
                    this[from] === elt)
                return from;
        }
        return -1;
    };

Upvotes: 0

InvisibleWolf
InvisibleWolf

Reputation: 1017

Here is my solution

function Search()
{

    if (All_Titles.indexOf(User_Input)>-1)
    {
        alert("yes");
    }
    else
    {
        alert("No matched movies");
    }

}

Upvotes: 0

Sunny Singh
Sunny Singh

Reputation: 86

Use a loop to iterate through all the titles, comparing each with the user input

function Search() {
    User_Input = User_Input.trim();
    var i, len, title;
    len = All_Titles.length;
    for(i = 0;  i < len; i++){
       title = All_Titles[i].innerHTML.trim();
       if(User_Input === title){
           document.writeln("It worked!");
           return;   
       }
    }

    if(i === len){
         alert("No matched movies");
    }
}

Upvotes: 0

Related Questions