Steffi
Steffi

Reputation: 7087

How to append variable to url in jquery?

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

Upvotes: 7

Views: 26328

Answers (4)

JohnC
JohnC

Reputation: 1387

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

Upvotes: 10

zoombaro
zoombaro

Reputation: 27

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

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

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

Upvotes: 12

Šime Vidas
Šime Vidas

Reputation: 186083

$('a').attr('href', function(i, v) {
    return v + 'text...';
});

Upvotes: 2

Related Questions