0

Hi im using following code to get the query string value in a form field:

<script>
var url = window.location.search;
url = url.replace("?Id=", ''); // remove the ? 
</script>
<script>document.write("<input name='Id' data-constraints='@Required(groups=[customer])' id='Id' type='text' value='"+url+"' />");</script>

if i visit [this is not a link] (http://mydomain.com/?Id=987) it records the Id in field but when more parameters are included it also records in the field, i want only first or any specific query string parameter to be added in form field?

  • 1
    Did you use any search? http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter http://stackoverflow.com/questions/11582512/how-to-get-url-parameters-with-javascript –  Feb 18 '14 at 03:47
  • possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) –  Feb 18 '14 at 03:47

2 Answers2

2

How about building an nice little associative array out of your query string parameters, something like:

var urlParams = [];
window.location.search.replace("?", "").split("&").forEach(function (e, i) {
    var p = e.split("=");
    urlParams[p[0]] = p[1];
});

// We have all the params now -> you can access it by name
console.log(urlParams["Id"]);
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
0

Basically, you need to check for the existence of an ampersand, the get the sub string up to the ampersand.

You could add this code after you do your replace:

var start = url.indexOf('&');

if(start > 0) {
    url = url.substring(0, start);
}
Sam
  • 2,166
  • 2
  • 20
  • 28