Home > Back-end >  search input on JAVASCRIPT
search input on JAVASCRIPT

Time:01-21

how to make an input like on the google site? I need that after entering the texts and in the input, Google opens with the desired request.

on JAVASCRIPT

google's input
1

2

my input(html) <input type="search" placeholder="Search in Google">

CodePudding user response:

if you mean redirect to a google page after input this would work

document.querySelector('.finder').addEventListener('focusout',function(){
location.replace("https://www.google.com/search?q="       document.querySelector('.finder').textContent);
});

this will send the user to a google page with the needed requests when they leave the input fild

if you need to make something simular but on your oun website the best option would be to send the user to a nother page with the query data in the url and some back end to construct and return a needed page.

or you could send a fetch and get info back on focus out

CodePudding user response:

You can add an event listener to let's say a button,when that button is clicked.
The value in your search field will be added to the end of a google search link.

However, since you can expect people to type sentences (and urls don't use spaces), you can use replace() to replace all spaces with, in our case, a ' ' (url format for spaces is ' ', but spaces in queries are commonly replaced with a ' ' character).

Lastly, you can use window.open(), to open a new window that uses our link.

Here's an example:

const SEARCH_GOOGLE = document.getElementById('SEARCH_GOOGLE');

SEARCH_GOOGLE.addEventListener("click", () => {
  let value = document.getElementById('SEARCH_GOOGLE_VALUE').value;
  value = value.replace(' ', ' ');

  let link = "https://www.google.com/search?q="   value;
  window.open(link);
});
  • Related