Home > database >  How to make a simple Search Bar using html/css/js
How to make a simple Search Bar using html/css/js

Time:07-02

this is another attempt to learn web development basics.

I've created a simple search bar.

what I want to do is: If we type anything in the provided text box then I press the search button or enter key, t searches the provided text on google.

I want to know how we can code this using JS

let textInput=document.querySelector('.textInput');
let searchBtn=document.querySelector('.searchBtn');

searchBtn.addEventListener('click',()=>{
    
});

searchBtn.addEventListener("keydown", (e)=> {
    if (e.key === "Enter") {
       
    }
});
body{
    display: grid;
    place-items:center;
    height: 100vh;
    align-content: center;
    justify-content: center;
}

.textInput input{
    width: 300px;
    height: 30px;
}

h3 {
    margin-bottom: 10px;
}

.searchBar{
    display: flex;
    align-items: center;
}
.searchBtn{
    width: 50px;
    height: 36px;
    background-color: rgb(192, 192, 192);
    display: grid;
    place-items: center;
    cursor: pointer;
}

.searchBtn img{
    width: 30px;
    height: auto;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styleSheet.css">
    <title>Document</title>
</head>
<body>
    <div ><h3> HELLO SEARCH</h3></div>
    <div >
        <div >
            <input type="text" placeholder="Search Enything">
        </div>
        <div ><img src="https://img.icons8.com/ios-glyphs/60/000000/search--v1.png"/></div>
    </div>
    <script src="app..js"></script>
</body>
</html>

thank you!

CodePudding user response:

You don't need JavaScript to make it search on google. You can just add a form action that makes it go to google. Just change your HTML to:

<div >
  <h3> HELLO SEARCH</h3>
</div>
<form action="https://www.google.com/search">
  <div >
    <div >
      <input type="text" name="q" placeholder="Search Enything">
    </div>
    <button type="submit" >
      <img src="https://img.icons8.com/ios-glyphs/60/000000/search--v1.png" />
    </button>
  </div>
</form>

CodePudding user response:

Try using this JavaScript

let textInput=document.querySelector('.textInput');
let searchBtn=document.querySelector('.searchBtn');

searchBtn.addEventListener('click',()=>{
    
});

searchBtn.addEventListener("keydown", (e)=> {
    if (e.key === "Enter") {
      
       var text = document.getElementById("inputid");
       location = `google.com/search?q=${text}&safe=active` 
       
    }
});

And add an id attribute to your input field, and replace the above "inputid" with the value of the id.

  • Related