0

I had a simple form that displays the submitted data in a below div with jQuery

  <form id="form" action="">
    <div class="form-group">
      <input type="text" class="form-control" name="firstname" />
    </div>
    <div class="form-group">
      <input type="text" class="form-control" name="lastname" />
    </div>
    <button id="button" class="btn btn-default">Generate</button>
  </form>

When you submit that button, the content is displayed on a div called #results thanks to a small piece of jQuery:

$(document).ready(function(){
  $("button").click(function(){
    var data = $("form").serializeArray();
    $.each(data, function(i, field){
        $("#results").append(field.name + ": " + field.value + "<br>");
    });
  return false;
  });   
});

As I serialize the array, the URL looks like this ?firstname=john&lastname=doe

I would like that when people access that URL, the data displayed in my #results div takes the URL parameters into account and displays it accordingly. Any clue?

Marwann
  • 163
  • 3
  • 14
  • 3
    [How to get querystring values in JS](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript). From there you can use `val()` to set the appropriate elements' `value` attribute – Rory McCrossan Oct 01 '16 at 18:16
  • `window.location.search` will return the query string `?firstname=john&lastname=doe` which can then be parsed – varontron Oct 01 '16 at 18:20
  • @RoryMcCrossan Thank you. Problem solved. – Marwann Oct 03 '16 at 14:04

1 Answers1

0

Using the following function (as suggested in the comments) enabled me to get the querystring values.

  function getQueryVariable(variable)
{
   var query = window.location.search.substring(1);
   var vars = query.split("&");
   for (var i=0;i<vars.length;i++) {
           var pair = vars[i].split("=");
           if(pair[0] == variable){return pair[1];}
   }

   return(false);
}

I then displayed them that way :

var querystringname = getQueryVariable("querystringname");
var querystringnamedecoded = decodeURIComponent(querystringname); //if it has a space or special characters, it'll strip the %20 (and likes) and replace them by the actual character
$.("#divwhereyouwanttodisplayyourcontent").append(querystringnamedecoded);
Marwann
  • 163
  • 3
  • 14