weidi
weidi

Reputation: 852

How to generate the content of an href link by the return value of a javascript function?

I have a javascript function:

function foo() { return "/a/b/SomeApi"; }

then I have a href link in my web page. I want this link to point to the value returned by my javascript function, so that when the user clicks the link, it's as if the user had clicked a link with url /a/b/SomeApi.

I tried following:

<a href="javascript:foo()">Click</a>

But the result of this is the browser would open a new window showing the literal value /a/b/SomeApi instead of sending a request to the server.

Any suggestions? Thanks.

Upvotes: 2

Views: 2098

Answers (2)

freefaller
freefaller

Reputation: 19953

Instead of returning the string, set the location of the current page with it, like this...

function foo() { document.location.href = "/a/b/SomeApi"; }

As pointed out by @haim770 - these are not the droids you are looking for.

If you want to specifically set the href attribute, you must do it from outside of the link. Firstly you should give your link an id attribute, such as this...

<a id="myAnchor">Click</a>

This piece of code should then be placed either after the element in the page, or as part of a "document loaded" piece of code.

document.getElementById("myAnchor").href = "/a/b/SomeApi";

If you were using jQuery (which is not in your list of tags) you could do something like this...

$(function(){
  $("#myAnchor").attr("href", "/a/b/SomeApi")
});

Upvotes: 1

Nick Andriopoulos
Nick Andriopoulos

Reputation: 10643

I don't think HREF was ever meant to be dynamic; for that, just use the onclick property, such as :

<a href="#" onclick="window.location.assign(foo())">Click</a>

Upvotes: 0

Related Questions