javascripthtmlforms

Create a multi-choice search bar


I'm trying to make a simple HTML webpage with a search bar that would be able to query the external search engine of the user's choice (selected in a dropdown menu).

I'm unable to make the user's choice be accepted by the code. Here's what I have:

<html>
<div class="custom-select" style="width:200px;">
  <select>
    <option value="http://www.google.com/search">Google</option>
    <option value="http://www.bing.com/search">Bing</option>
    <option value="https://duckduckgo.com/?q=">Duckduckgo</option>
  </select>
</div>
<div class="search-bar">
  <form method="get" action="???">
    <div style="border:1px solid black;padding:4px;width:20em;">
      <table border="0" cellpadding="0">
        <tr>
          <td>
            <input type="text" name="q" size="25" maxlength="255" value="" />
            <input type="submit" value="Search" />
          </td>
        </tr>
      </table>
    </div>
  </form>
</div>
</html>


Solution

  • This can be done with javascript by setting the action attribute of the <form> just before the search request is fired.

    Note: this does not work from inside the Stack Overflow snippet for reasons that I can't quite figure out (possibly a Content Security Policy), but I confirmed that it works in a standalone HTML file.

    function UpdateFormAction() {
      var url = document.getElementById("myDropdown").value;
      document.getElementById("myForm").action = url;
    }
    <html>
    <div class="custom-select" style="width:200px;">
      <select id="myDropdown">
        <option value="http://www.google.com/search">Google</option>
        <option value="http://www.bing.com/search">Bing</option>
        <option value="https://duckduckgo.com/?q=">Duckduckgo</option>
      </select>
    </div>
    <div class="search-bar">
      <form id="myForm" target="_blank" method="get" action="???" onsubmit="UpdateFormAction()">
        <div style="border:1px solid black;padding:4px;width:20em;">
          <table border="0" cellpadding="0">
            <tr>
              <td>
                <input type="text" name="q" size="25" maxlength="255" value="" />
                <input type="submit" value="Search" />
              </td>
            </tr>
          </table>
        </div>
      </form>
    </div>
    
    </html>