anon10023108
anon10023108

Reputation: 141

search bar that search's on google from your website

I add an input search bar that takes the user inputted text and searches it on google but it's somehow not working. I tried debugging if the problem was from the search button by setting an alert function that gets triggered on img click and It worked fine. This means the issue is from my javascript function. The search should have worked but is not working. As a side question is there any way to open the search result on a different tab by target_ it. Any help is appreciated. Thanks in advance.

function searchGoogle() {
  document.getElementById("searchButton").href =
    (("https://www.google.com/search?q=") + (document.getElementById("searchInput").value));
}
.form-group {
  width: 70%;
  position: absolute;
  top: 3%;
  left: 5%;
}

.form-group img {
  width: 10%;
  position: absolute;
  top: 10%;
  right: 5%;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>


<div class="form-group">
  <input type="text" class="form-control" id="searchInput" placeholder="Google Search">
  <img id="searchButton" src="https://img.icons8.com/material-outlined/128/000000/search--v1.png" onclick="searchGoogle()" />
</div>

Upvotes: 1

Views: 605

Answers (1)

StackSlave
StackSlave

Reputation: 10617

Quick fix:

let searchGoogle; // for use on other loads
addEventListener('load', ()=>{
const searchInput = document.getElementById('searchInput'); // why get it again?
searchGoogle = ()=>{
  location = 'https://www.google.com/search?q='+searchInput.value;
}
});

Upvotes: 2

Related Questions