0

I have a number of values that are being passed via the URL, that I need to capture in an array, to replace text elements on a page. For example:

URL: http://www.domain.com/?client=ClientName&project=ProjectName

I'm looking to have a simple piece of html which will have the values inserted. For example

<ul>
  <li>Client: <span class="client"></span></li>
  <li>Project: <span class="project"></span></li>
</ul>

This should produce:

  • Client: ClientName
  • Project: ProjectName

It is possible that the pieces of data will need to be written a number of times on a page, hence the use of the span tags with classes.

Can anyone advise as to how this can be achieved using jQuery. Thank you in advance for any suggestions.

3
  • Is there a reason you can't do this on the server side? That would be so much simpler... Commented Oct 3, 2012 at 19:29
  • The final page is a static HTML file. I'm just looking to pop in some personalised content & presumed this would be the simplest way to achieve it. What alternative do you suggest? Commented Oct 3, 2012 at 19:32
  • var params = jquery.param(object) api.jquery.com/jQuery.param Commented Oct 3, 2012 at 19:38

1 Answer 1

1

I think you need something like that: http://jsfiddle.net/8WTA6/2/

var params = window.location.search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
    var param = params[i].split('=');
    $("." + param[0]).html(param[1]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is fantastic thanks! This is a little beyond my current understanding of the code. Any chance you could point me to some relevant documentation so I can read up. Thanks again.
Let's take a look. w3schools.com/jsref/obj_location.asp - here is about location object. w3schools.com/jsref/jsref_split.asp - here is about splitting string to array of strings. We're doing it twice: first time to split by "&" and get "key=value" strings, second - to split it by "=". api.jquery.com/html is about .html() and api.jquery.com/class-selector is about class selector. Hope this helps.
Awesome thank you so much for your help!! Just quickly, so that I can get this to work with elements that have spaces (i.e. "Client Name"). I presume I can use decodeURI but I'm not sure how to integrate it in the above. Can you advise??? (bit cheeky I know)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.