Tuesday, March 19, 2013

Set the HTML form with data from in the page's address


Use JQuery to fill in a Web form when post-back to the page using method="get".

Assume the a Web page has the following address http://localhost:/Example01.htm and contains the following simple HTML form:


The source code of that form may appear as following:

<form action="Example01.htm" method="get">

  <input id="QueryString" type="text" name="QueryString" />

  <select id="Method" name="Method">
    <option value="And">All Words</option>
    <option value="Or">Any Word</option>
  </select>

  <input type="submit" value="Submit" />

</form> 


Upon submit of the form, which references the current page in the forms action parameter, the page's address is updated with the values from the QueryString and Method input fields:

http://localhost:/Example01.htm?QueryString=my+query+terms&Method=And

The following JavaScript parses the address parameters to re-set the form with the data provided by the user:



<script src="jquery-1.9.1.min.js" type="text/javascript"></script>

<script language="javascript" type="text/javascript">


$(document).ready(function () {

    var vQueryString = getURLParam("QueryString");
    $("#QueryString").val(vQueryString);

    var vMethod = getURLParam("Method");
   $("select#Method option").each(function () {
 if ($(this).val() == vMethod) {
     $(this).prop('selected', true);
 }
    });

});

function getURLParam(name){
 return decodeURIComponent((new RegExp('[?|&]' +
    name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || 
    [, ""])[1].replace(/\+/g, '%20')) || null;
}
</script>