创建多选搜索栏

时间:2018-08-13 07:23:43

标签: javascript html forms

我正在尝试用搜索栏制作一个简单的HTML网页,以便能够查询用户选择的外部搜索引擎(在下拉菜单中选择)。

我无法使代码接受用户的选择。这是我所拥有的:

<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>

2 个答案:

答案 0 :(得分:2)

您将无法仅使用html或css来执行此操作。最好的选择是使用javascript从不同的搜索引擎进行api调用。

google搜索api是here

Bing搜索api是here。请注意,某些功能会花钱。

duckduckgo搜索api是here

您还应该研究Jquery,异步编程和JSON。您很可能会使用Jquery的Ajax从每个搜索引擎请求数据,并且必须能够解析json,然后使用js更改html。

答案 1 :(得分:1)

这可以通过使用javascript通过在触发搜索请求之前设置 action <form> 属性来实现。

注意:由于我无法弄清楚(可能是内容安全策略)的原因,这在Stack Overflow片段内部不起作用,但我确认它可以在独立的HTML文件中使用。

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>