How can I trigger an action without clicking a button with Javascript?

Viewed 605

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?

3 Answers

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>

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

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>
Related