简体   繁体   中英

Javascript onKeyUp

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

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) {

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.

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