【问题标题】:Simple Form Submit Code简单表单提交代码
【发布时间】:2010-12-11 04:21:22
【问题描述】:

我想创建一个只有输入文本框和搜索按钮的简单表单。

人们会在框中输入搜索词并按搜索。

所有要做的就是获取他们的搜索词并将其添加到 url 的末尾。

因此,如果搜索词是“美味的意大利食物”,提交按钮会将用户发送到 http://domain/find/good意大利食物

最简单的方法是什么?

谢谢!

【问题讨论】:

    标签: javascript html forms


    【解决方案1】:
    <html>
      <head>
        <script type='text/javascript'> 
          function Search() {
            var keyword = document.getElementById("keyword").value; 
            var url = "http://yourwebsite.com/find/"+keyword; 
            window.location = url; 
            return false;
          }
        </script>
      </head>
      <body>
        <form name="search">
          <input type="text" name="keyword" id="keyword" />
          <input type="button" name="btnser" onclick="Search()" value="Search" />
        </form>
      </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      我还建议使用 encodeURI() 使其“安全”。

      http://www.w3schools.com/jsref/jsref_encodeuri.asp

      【讨论】:

        【解决方案3】:

        使用 javascript 和 html 表单

        创建一个带有按钮和文本框的表单 在表单的帖子中调用 javascript 函数来创建带有用户输入文本的 url

        <!DOCTYPE html>
        <html>
        <head>
        <script type='text/javascript'>
          function redirect(){  
            var s = document.getElementbyID("txt").value;
            var url="http://url.com/" + s;
            window.location = url;
          }
        </script>
        </head>
        <body>
          <form>
            <input type=''></input>
          </form>
        </body>
        </html>
        

        【讨论】:

          【解决方案4】:

          您可以在 onsubmit 事件中覆盖 action 属性:Example

          HTML

          <form action="#" onsubmit="send(this)" method="post" target="_blank" >
              <input id="text"/>
              <input type="submit" value="submit"/>
          </form>
          

          JavaScript

          function send( form){
              form.action = location.href + '/'+encodeURI(document.getElementById('text').value);
          }
          

          此外,在onsubmit 事件中覆盖表单操作或重定向用户将允许您使用真正的submit 按钮。

          这使用户能够在完成输入后直接点击enter key 来提交搜索,而无需编写额外的逻辑来监听文本框中的输入键来提交搜索。

          【讨论】:

          • 谢谢。总有一个?在网址的末尾。我该如何删除它?
          • 哇哦,没注意到。如果您将表单方法设置为 method="post" 它应该摆脱 ?
          猜你喜欢
          • 2013-11-27
          • 1970-01-01
          • 1970-01-01
          • 2016-06-06
          • 2012-01-29
          • 1970-01-01
          相关资源
          最近更新 更多