Reputation: 3589
so I'm working on a mock version of google censorship for history class. I'm trying to get the search to work upon pressing enter, but so far all I get is a search upon the first letter I enter. Any suggestions?
HTML code:
<form id="searchBox">
<input type="text" id = "search" name="search" size="85" onKeyUp="searchCensor()"/><br />
</form>
JavaScript Code:
function searchCensor()
{
var keyTerms = document.getElementById("search").value;
if(keyTerms == "censorship")
window.location = "http://andrewgu12.kodingen.com/history/censor.php";
else if(window.event.keyCode == 13)
window.location = "https://www.google.com/search?q="+keyTerms;
else
window.location = "https://www.google.com/search?q="+keyTerms;
}
Upvotes: 2
Views: 4860
Reputation: 60717
Here is your logic:
If the search field has the value "censorship", go straight to this page
Else, if the key hit was [Enter], search on google the value of the search field
Else, in any other case, search on google the value of the search field
Now, say, you're hitting "e" in your search field. What happens?
First check: it's not "censorship", skip
Second check: the hit key is not [Enter], skip
Third check: Alright, none of the checks before passed, I'm doing this.
So you end up searching on Google for the letter "e".
Do you see how this is wrong?
That said, take off the else
and you'll be fine.
Upvotes: 0
Reputation: 1323
You need to check which key is being pressed ... you are running your function each time ANY key is being pressed right now. Inside your searchCensor() function you will want to have a check like this: if (event.keyCode == 13) {
Upvotes: 1