Search code examples
htmlwebsearchsearchbar

Html Search with top 5 before the search


I have a problem on my website. I hope someone has an Idea how to fix it.

I want to do a built in search bar for my website which searches Google for the search word but adds top 5 before it so like: top 5 [search word]. (If the user types in bananas for instance, the website would open a new window with a Google search for: top 5 bananas)

I tried to find out how i could make this possible but I have no Idea how to do this.

I tried to build a html form:

            <form action="https://www.google.com/search" method="GET">
                <input type"text" name="q" placeholder="Search">
                <input type="submit" value="Search">
                </form>

But i can´t put the get form action to https://www.google.de/search?&q=top+5

I hope you can help me with my question.


Solution

  • @Terox For your use-case, you need to dynamically update the user value and simply using HTMl it's not possible. You need to use javascript and before user press "submit" button, you have to get the user input and prepend the "default string" before that. The form action won't help you in that case, you can use below code for this particular use case

    <script type="application/javascript">
        // get elements of the form
        const form = document.querySelector("#searchForm");
        const inputBox = document.querySelector("#inputBox");
    
        // add a listener to update the value on form submit
        form.addEventListener("submit", event => {
            // prevents automatic submit of the form and lets you update the value
            event.preventDefault();
    
           // takes you to different url and append your custom string before
            window.location.href = 'https://www.google.com/search?q=top+5+' + inputBox.value;
        });
    </script>
    

    Read more about it here