Wednesday, 10 September 2014

How to build query string in javascript?






This article will discuss 'How to build query string in javascript?'. Copy and paste this html code in your page's body tag. 
<input id="Txtname" placeholder="Name" name="Txtname" /> <input id="Txtmobile" placeholder="Mobile" name="Txtmobile"/> <input id="Texemail" placeholder="Email Id" name="Texemail" /> <input type="submit" id="submit" title="Submit" value="Submit" onclick="sendm()" />


On button click below code will fetch text from text-boxes, build query string and redirecting to that query string. Here 'buildUrl' is a function that builds & returns query string.
<script type="text/javascript"> function buildUrl(url, parameters) { var qs = ""; for (var key in parameters) { var value = parameters[key]; qs += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&"; } if (qs.length > 0) { qs = qs.substring(0, qs.length - 1); //chop off last "&" url = url + "?" + qs; } return url; } function sendm() { var url = "Form.aspx"; var parameters = new Array(); parameters["name"] = document.getElementById('Txtname').value; parameters["mobile"] = document.getElementById('Txtmobile').value; parameters["email"] = document.getElementById('Texemail').value; var site = buildUrl(url, parameters); window.location = site; } </script>

No comments:

Post a Comment