1

I'm building a website, and there is a input that allows the user to write some text and search for it on google. I have everything working already, except that the user has to click the search button to make it go to google.

I wanted to be able to press enter key and it search. Is there any way?

code:

<img id="google-logo" src="1280px-Google_2015_logo.svg.png">
    <input placeholder="Pesquisar na Web" id="google-search">
    <img src="search.png" id="search-img" value="Submit" onClick="javascript: window.location.replace('http://www.google.com/search?q=' + document.getElementById('google-search').value);">

3 Answers3

0

You might want to start a keydown event listener. whenever a key is pressed this event will fire. One of the parameters is the keyCode. When the pressed key's keycode is equal to the enter key's keycode, then fire the rest of the code.

document.addEventListener("keydown", (e) => {
    if(e.keyCode === 13){
        "execute some code"
    }
});

this should do the job.

0

The question has already been answered here: Trigger a button click with JavaScript on the Enter key in a text box

Or, add this script tag to your html code:

<script>
document.getElementById("google-search")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("search-img").click();
    }
});
</script>
Kaushik
  • 133
  • 13
0

Maybe like this:

<img id="google-logo" src="1280px-Google_2015_logo.svg.png">
<input placeholder="Pesquisar na Web" id="google-search">
<img src="search.png" 
     id="search-img" 
     value="Submit" 
     onClick="javascript: window.location.replace('http://www.google.com/search?q=' + document.getElementById('google-search').value);" 
     onkeydown = "if(event.keyCode == 13){document.getElementById('google-search').click();}">
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17