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