Search code examples
javascriptprototypejstapestry

Fetch and Replace href attribute value of <a> tag using prototype


I have a simple link inside my tml (apache tapestry specific) :

<a href="www.google.com" class="info-value" target="new">www.google.com</a>

Now on the browser if I am trying to click the link, actually it's redirecting to

http://localhost:8080/..../..../www.google.com

Instead of it should open a new tab for that link.

So the logic which I am thinking is :

1) Fire a javascript on page load
2) Get the href value of anchor tag 
3) Append http:// at the start, if it doesn't contains it.

So to do this, actually I want to use prototype (javascript framework), and I am bit new to this...

How can I write the function using the Prototype.js library?


Solution

  • You don't say where the value for your href is coming from. As you say you need to prepend an "http". Assuming the link is dynamically rendered, why don't you just do this server-side, probably much easier. In tml:

    ... href="${url}" ....
    

    and in .java:

    public String getUrl() {
      return "http://" + url;
    }
    

    This is a much better approach than doing it client-side as what happens if the user has javascript turned off?

    On the other hand, if it's a static link in your .tml, just write "http://www.google.com"!

    Edit: In light of your comment below:

    public String getUrl() {
    
       if (!url.startsWith("http://") {
          url = "http://" + url;
       }
    
       return url;
    }
    

    The above is just an example of what do do. You can either add another method to activityDetails which does this (e.g getExternalLinkWithProtocol()), or provide a wrapper method similar to the one above.