2

I made a text input to enter some text and search it on google.

<input type="text" placeholder="type search word and press Enter to google" id="text" />
<input type="button" id="btn" value="search" onClick="javascript:
window.open('https://www.google.com/search?q=' + document.getElementById('text').value);" />

<script>
var input = document.getElementById("text");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   event.preventDefault();
   document.getElementById("btn").click();
  }
});
</script>

I want to get rid of the search button and integrate the googling function only through pressing Enter. How can I do this?

0

3 Answers 3

2

Fiddle

Using a form and ES6 syntax is the easiest and most efficient method:

const $form = document.getElementById('form')
const $input = document.getElementById('input')

$form.addEventListener('submit', (evt) => {
  evt.preventDefault()
  window.open(`https://google.com/search?q=${$input.value}`)
})
<form id="form">
  <input type="text" placeholder="Search Google" id="input" />
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

Upvoting since it's a good answer. But the run code snippet part doesn't seem to do anything when I press enter in the text input, which makes it useless. I'd consider getting rid of that, especially since you provided the fiddle link which does work.
@paxdiablo if you press enter in the text input and open your browser console, you will see the following error: Blocked opening 'https://google.com/search?q=' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set., which proves that the example is working. The error occurs because the Stack Snippet is being hosted on a different domain, stacksnippets.net.
0

Here is working demo: https://jsfiddle.net/usmanmunir/t1djucrx/2/

var input = document.getElementById("text");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   event.preventDefault();   
   window.open('https://www.google.com/search?q=' + document.getElementById('text').value);
  }
});

Comments

0

if you want to completely remove the button, then instead just put the code from the button in a javascript function, and call that when enter is pressed, so

<input type="text" placeholder="press Enter to google" id="text" />


<script>
var input = document.getElementById("text");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   event.preventDefault();
   window.open('https://www.google.com/search?q=' + document.getElementById('text').value);
  }
});
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.