繁体   English   中英

将字符串追加到表单输入

[英]Append string to form input

我得到了这个表格:

<form class="navbar-form navbar-right" role="search" action="https://www.google.com/search" target="_blank">
<div class="form-group">
<input id="search" type="text" name="q" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>

当用户点击搜索按钮时,我想在输入中添加一个字符串。

例如,当用户输入“ Foo”并提交表单时,我希望最终URL为https://www.google.com/search?q=FooSTRING而不是https://www.google.com/search?q=Foo

我将如何实现这一目标?

将事件处理程序添加到表单提交中,该表单将字符串附加到输入之前。 另一篇StackOverflow文章中

window.onload = function() {
    document.getElementById('theForm').onsubmit = function() {
        var txt = document.getElementById('txtSearch');
        txt.value = "updated " + txt.value;
    };
};​

很显然,您必须修改选择的id以使其与HTML匹配才能起作用。

如果要在JQuery中执行此操作:

$('#theForm').submit(function() {
    var txt = $('#txtSearch');
    txt.val("updated " + txt.val());
});

您可以在按下更改输入值的按钮(从而更改最终URL)时创建onclick事件。 这是代码:

<!DOCTYPE html>
<html>
  <head>
    <script>
        function addString()
        {
            var x = document.getElementById("search");
            x.value = x.value + "STRING";
        }
    </script>
  </head>
  <body>
    <form class="navbar-form navbar-right" role="search"    action="https://www.google.com/search" target="_blank">
      <div class="form-group">
        <input id="search" type="text" name="q" class="form-control"     placeholder="Search">
      </div>
      <button onclick="addString()" type="submit" class="btn btn- default">Search</button>
    </form>
  </body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM