追加字符串以形成输入

时间:2015-03-12 02:47:56

标签: javascript jquery html

我收到了这张表格:

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

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

例如,当用户输入&#34; Foo&#34;并提交表单,我希望最终的网址为https://www.google.com/search?q=FooSTRING,而不是https://www.google.com/search?q=Foo

我将如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

向表单提交添加一个事件处理程序,该字符串将在输入之前将字符串附加到输入。来自another StackOverflow article

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());
});

答案 1 :(得分:-1)

按下更改输入值的按钮可以进行onclick事件,从而更改最终的URL。这是代码:

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