Reputation: 835
I am learning jquery now. I want to replace the parameters of a url with another on page load. For example here is my code
<div class="changeparam">
<a href="http://demo.org/post.php?i=123&p=456&s=789">Link</a>
</div>
Now I need to change the value of the params i,p and s to different values say abc,def,ghi respectively. How can i do it on page load?
Upvotes: 1
Views: 6810
Reputation: 2311
Try using the jQuery BBQ plugin. It makes dealing with querystrings much less of an issue.
I think you'd want to try
$(document).ready(function(){
$.param.querystring($(".changeparam").attr("href"), {i:123, p:456, s:789})
});
It's got a lot of cool stuff for manipulating querystrings and you don't have to reinvent the wheel here.
Upvotes: 2
Reputation: 6043
Do you need to know the old values? If not can't you do something along the lines of the following (this assumes the simple case that all links will have the same query string and would need to be extended if this is not the case):
$(document).ready( function ( ) {
// Get the full address from the original link
var old_fulladdr = $('div.changeparam a').attr('href');
// split it to get the actual file address
var old_addr_parts = old_fulladdr.split('?');
// This may need something more complex...
var new_querystring = 'i=abc&p=def&g=ghi';
// This changes the href of the link to the new one.
$('div.changeparam a').attr('href',old_addr_parts[0] + '?' + new_querystring);
});
UPDATE: I've created a more flexible function that takes a querystring, an array of items to be replaced and an array of replacement values then outputs a new query string. Have a look at this jsfiddle: http://jsfiddle.net/LWzZR/1
Also, I agree with the commenters on your question - whilst it's possible, it's not recommended :)
Upvotes: 3