Javascript - Get URL Parameters from Form Submit

This example illustrates how Javascript extracts name and value pairs from a 'GET' submission or an url. You can use this as a means to pass Javascript values from one HTML page to another.

This code will extract name/value pairs from a URL such as http://codediarie.com/test.html?name=charlie&address=15%20Monterey%20Place%20Cherrybrook%20NSW%Australia.
 1. function MyGetUrlParams(){
 2.   var url_params = new Array();
 3.   var urla = location.href.substring(location.href.indexOf('?')+1).split('&');
 4.   for(i=0;i< urla.length ;i++){
 5.     url_params[urla[i].substring(0,urla[i].indexOf('='))]=
 6.     urla[i].substring(urla[i].indexOf('=')+1);
 7.   }
 8.   return url_params;
 9. }
10. 
11. ...
12. #stuff
13. ...
14. 
15. alert(MyGetUrlParams()['name']);
16. alert(MyGetUrlParams()['address']);
17. 
18. var params = MyGetUrlParams();
19. for (i in params){
20.   alert(params[i]);
21. }
Hide line numbers
Line 3 We decode location.href and put the values into an associative array with the names as keys.

Line 15-21 We can then use this array to get the values using the names - in many ways.

No comments: