How to pass input field values as a url query stri

2019-06-03 22:04发布

问题:

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

回答1:

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/



回答2:

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>