0

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?

2 Answers 2

2

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());
});
Sign up to request clarification or add additional context in comments.

2 Comments

I already tried doing that however it doesn't feel right. It 'pollutes' the field; yes I can add more code to restore it or clear it after the submission but there must be a better solution than this.
It doesn't pollute the field, it does what you want and frankly, it's the only easy way to do what you want.
-1

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>

2 Comments

already tried doing that however it doesn't feel right. It 'pollutes' the field; yes I can add more code to restore it or clear it after the submission but there must be a better solution than this
This won't always work if the form is submitted by pressing enter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.