简体   繁体   中英

Append string to form input

I got this form:

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

When a user hits the search button I want to add a string to the input.

For example, when a user types in "Foo" and submits the form, I want for the final URL to be https://www.google.com/search?q=FooSTRING instead of https://www.google.com/search?q=Foo .

How would I go about achieving this?

Add an event handler to the form submit that appends the string to the input before it's POSTed. From another StackOverflow article :

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

You'd obviously have to modify the id selects to match your HTML for this to work.

If you want to do it in JQuery:

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

You can make onclick event when pressing the button that changes input value, therefore changing final URL. Here is the code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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