4

I would have to input fields like this

 <form>
    <input type="text" id="keyword" placeholder="XXX">
    <input type="text" id="state" placeholder="XXX">
    <button type="submit" id="submit">Submit</button>
 </form>

On click of the submit I would like to send them to a new page with the value of the input appended to the url with query string.

 http://www.link.com/page?keyword=XYXYX&state=XZXX

Here is my start thinking but was thinking .serialize() can handle this better than this example

  var keywordVal = $("#keyword").val();
  var stateVal = $("#state").val();

  $( "form" ).on( "submit", function() {
   event.preventDefault();
   location.href='http://www.link.com/page?keyword=' + keywordVal + '&state=' + stateVal
  });

let me know if i am approaching it the right way..

Community
  • 1
  • 1
nolawi
  • 4,439
  • 6
  • 22
  • 45
  • 1
    Add `method="get"`, `action="page"` and a `target` attribute to your form, and you don’t need JavaScript … (and will therefor be much less likely to get caught in any popup blocker.) – CBroe May 14 '15 at 15:49

2 Answers2

14

You don't need JavaScript to do this.

Simply add an action attribute with the URL and set the method attribute to GET (this will append the named field values as a query string).

<form action="<yourURL>" method="GET">
    <input type="text" id="keyword" name="keyword" placeholder="XXX">
    <input type="text" id="state" name="state" placeholder="XXX">
    <button type="submit" id="submit">Submit</button>
</form>

NOTE: You'll need name attributes on your fields.

Fiddle: http://jsfiddle.net/pjh7wkj4/

Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
3

No need any jQuery/javascript to do that, form tag is providing those functionality. Adding action and method (GET) attributes will give you the results what you expect.

<form action="<target_url>" method="GET">
    <input type="text" id="keyword" name="keyword" placeholder="XXX">
    <input type="text" id="state" name="state" placeholder="XXX">
    <button type="submit" id="submit">Submit</button>
 </form>