Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass input field values as a url query string that will be opened on click of a submit button?

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

like image 686
nolawi Avatar asked Dec 02 '22 17:12

nolawi


1 Answers

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/

like image 131
Kevin Boucher Avatar answered Dec 05 '22 05:12

Kevin Boucher