Eddie
Eddie

Reputation: 621

How to execute an anchor\href in my javascript?

I'm trying to figure this one out but my mind has just gone blank.

The reason I am trying to execute the anchor in the javascript is because i'm passing a variable into the href. It could be true or false.

Here is what I have\what I'm trying to do. Any help would be great.

if (date1 <= date2) {
   //I want to execute this anchor
   <a href="@{Application.openthispage(true)}"></a>
}else{
   //otherwise execute this anchor
   <a href="@{Application.openthispage(false)}"></a>
}

Upvotes: 2

Views: 5859

Answers (2)

Phil McCullick
Phil McCullick

Reputation: 7170

The window.location method posted by Eli is the correct way to visit a link using JavaScript. However, if you can use a link instead of a button, you could just set the href of the link in the onclick. Here is a sample jsFiddle that visits a different url based on whether one input is greater than the other: http://jsfiddle.net/jw3Pd/

So when the user clicks the link, set the href to whatever link you want the user to visit.

$("#someId").on("click", function () { 
   if (date1 <= date2) {
      //I want to execute this anchor
      $("#someId").attr("href", "@{Application.openthispage(true)}");
   } else{
      //otherwise execute this anchor
      $("#someId").attr("href", "@{Application.openthispage(false)}");
   }
});

Upvotes: 2

Eli Gassert
Eli Gassert

Reputation: 9763

You're looking at the problem wrong. An anchor is a static HTML element that, when clicked, changes the current window location (i.e. URL). The JS equivalent looks something like this: window.location.href = 'http://www.google.com';. So by setting window.location.href you will use JS to navigate to another URL.

Upvotes: 6

Related Questions