1

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.

Torf
  • 1,154
  • 11
  • 29
Terox
  • 119
  • 1
  • 9

1 Answers1

0

@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

Akansh
  • 1,715
  • 3
  • 15
  • 34
  • @Arkansh Gulati Thanks for your help but I couldn't integrate the code to my website. I put the script in the tags and this form into the tags:
    but it didn't work.
    – Terox Apr 27 '20 at 09:31
  • 1
    @Terox Please learn how to add Javascript on page for your usecase, e.g. https://www.w3schools.com/js/tryit.asp?filename=tryjs_whereto – Akansh Apr 27 '20 at 12:56