Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append variable to url in jquery?

How can I append variable/text to the attribute href in jquery ?

like image 836
Steffi Avatar asked Mar 27 '11 20:03

Steffi


4 Answers

You could use the .attr() function:

var foo = 'foo=bar';
$('a#foo').attr('href', function(index, attr) {
    return attr + '?' + foo;
});

or:

$('a#foo').attr('href', function() {
    return this.href + '?' + foo;
});
like image 157
Darin Dimitrov Avatar answered Nov 14 '22 00:11

Darin Dimitrov


You need to check if there is already a query string before appending items to the url based on the other examples you'd do something like.

var foo = 'foo=bar';
$('a').attr('href', function(index, attr) {
    return attr + (attr.indexOf('?') >=0 ? '&' : '?') + foo;
});
like image 40
JohnC Avatar answered Nov 14 '22 00:11

JohnC


$('a').attr('href', function(i, v) {
    return v + 'text...';
});
like image 28
Šime Vidas Avatar answered Nov 14 '22 01:11

Šime Vidas


If you use it repeatedly try .attr() as:

HTML: <a id='foo' href='#'>I am your father,.. nooooo</a>

var myparams = 'myvar=myvalue';
var myurl = 'TypeThe_NetscapeURL';
$('a#foo').attr('href', function() {
    return myurl + '?' + myparams;
});
like image 1
zoombaro Avatar answered Nov 14 '22 01:11

zoombaro