简体   繁体   中英

help, stuck with logic variable comparison loop, javascript

I have an input text box for search of input, the id of the text box is: id="search".

if a user enters 'cat' at first and hit search.

In the function, I get the value 'cat' by using the syntax:

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

After that, the user enter 'dog' in the search box and hit search using the same function.

The function would assign 'dog' to the input variable.

How would I compare the current value (dog) to the previously entered value (cat)?

I have tried to assign the original input with a statement, something like

var orig = input;

but that would only overwrite the original input with the new input.

What is the logical approach to this problem.

var original = "";

function searchHandler() {
   var input = document.getElementById("search").value;

   if(input != original) {
      //handle case if input is not equal to original
   }

   else {
     //handle case if input is equal to original
   }

   original = input;
}

This code will maintain a history of the last-entered value (only on the client-side). If you want to maintain more than one value then the solution is slightly more complex; you could use a stack.

One way is to have a list or set of previously searched words. That way, instead of assigning a variable a value, you add the search term to the list or set. Although that brings up the issue of whether or not you want the search history to be unbounded and if you want to store duplicate search entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM