Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
 
Is there a reason you can't do this on the server side? That would be so much simpler... –  lonesomeday Oct 3 '12 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? –  Sheixt Oct 3 '12 at 19:32
 
var params = jquery.param(object) api.jquery.com/jQuery.param –  RPM Oct 3 '12 at 19:38
add comment

1 Answer

up vote 1 down vote accepted

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]);
}
share|improve this answer
 
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. –  Sheixt Oct 3 '12 at 20:10
 
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. –  Smileek Oct 3 '12 at 20:20
 
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) –  Sheixt Oct 3 '12 at 20:35
 
$("." + param[0]).html(decodeURI(param[1])); –  Smileek Oct 3 '12 at 20:39
 
u sir are a hero! –  Sheixt Oct 3 '12 at 20:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.