views:

44

answers:

2

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.

A: 
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.

Vivin Paliath
Thank you, I will try this out. I am not familiar with JS syntax, but your solution implies that the original var declared outside of the function can be called/modified inside the function. Is that correct? I will try, but just asking to confirm.
Jamex
Yes; it is a global variable. It has to be declared outside the scope of the function. Otherwise the updated value will be lost once you exit the function.
Vivin Paliath
It works, thank you Vivin.
Jamex
A: 

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.

Jesse J
Thank you for the reply, but I am not familiar with JS to start digging yet.
Jamex