Page Designer
Page Designer

Reputation: 71

How can i get the value of first query string in a URL

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?

Upvotes: 0

Views: 2155

Answers (2)

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15158

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"]);

Upvotes: 2

Sam
Sam

Reputation: 2201

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);
}

Upvotes: 0

Related Questions