skip to Main Content

I am working on a search project. I am new to html, css, etc., and haven’t the slightest idea of how to accomplish this. Here is my idea in simplest form:

  1. User visits website.
  2. User finds search box (form) I created.
  3. User types something into search box.
  4. When the user clicks the search button, or presses enter, the website appends what the user typed into the search box and places it in this link and proceeds to follow the link:

https://www.example.com/results.aspx?q=(USER SEARCH HERE)

I have tried researching the topic but have not found anything useful on it. Everything is very unclear. If anyone can find a tutorial, or tell me what I might be doing wrong, that would be greatly appreciated. 🙂

Thanks in advance for any help that was given!

2

Answers


  1. All you need is an input element and submit button and a submit event listener to call when submitting the form ( when clicking the button for search or click enter ), and on the submit event listener you can get the value of the input and add it as a query params.

    For example.

    const search = document.getElementById("search");
    const handleSubmit = (e) => {
        e.preventDefault();
        window.location.href = `https://www.example.com/results.aspx?q=${encodeURIComponent(
            search.value
        )}`;
    };
    <form onsubmit="handleSubmit(event)">
      <input id="search" type="text">
      <button>Search</button>
    </form>
    Login or Signup to reply.
  2. This is the very default behaviour of a form with the action attribute applied:

    <form action="results.aspx">
      <input type="text" name="q">
      <button>Search</button>
    </form>

    Writing "Hello" in the input and pressing the search button or pressing enter, results in a URL like:

    https://www.example.com/results.aspx?q=Hello
    

    Giving the input another name, like name="search", results in a URL like:

    https://www.example.com/results.aspx?search=Hello
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search