1

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?

3
  • 4
    A small tipp for collaboration projects: please start functions and variable names with a lower case letter, only classes should start with a upper case letter. Also it has become common habit to name function as verbs, as they do something: validateInput() would be a great name. This will not only aid others in understanding your code but will also help you at maintenance later on. Commented Sep 23, 2014 at 8:49
  • Check this answer and this. Commented Sep 23, 2014 at 8:54
  • All_Titles is list of HTML's elements. therefore, operator == wouldn't work with string. See my answer below. Commented Sep 23, 2014 at 9:53

5 Answers 5

5

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>

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

4 Comments

Thanks man, problem is the school won't allow us to use JQuery this semester ><
jQuery is js extension. use it and don't listen to school teachers!
@user3521018 - as you asked i added also pure JS version.
Wow, it finally did work! I was using the wrong ID's for the input form at first, that is why your example didn't work out the first time. Thanks a lot!:)
1

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>

1 Comment

works fine. i love the way you show the demo of the solution.
0

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");
    }
}

2 Comments

I tried this just now and unfortunately nothing happens: If I enter a search word and press the submit button the page just refreshes and does nothing else. ValidateInput() still seems to be doing its' job though. Here is my HTML for the form, maybe that will be usefull.
<form name="search_form" class="search" onsubmit="return ValidateInput()"> <input type="text" title="Zoekbalk" name="input_box" placeholder="Typ hier om te zoeken" /> <input class="search_button" type="submit" value="Zoek" name="search_button"/> </form>
0

Here is my solution

function Search()
{

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

}

1 Comment

I tried this too but again, no reaction. Maybe the problem has something to do with my All_Titles var being a NodeList rather than an array?
0

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;
    };

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.