Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1747 How can I change the HREF attribute of a link when a form button is clicked?

irt.org | Knowledge Base | JavaScript | Link | Q1747 [ previous next ]

Q1747 How can I change the HREF attribute of a link when a form button is clicked?

The following works in Internet Explorer 4+ and Netscape Navigator 6+ using the id attribute to identify the required link. In other browsers you need to supply the original href attribute value of the link for the code to trawl through all the links in the document looking for the appropriate link:

<html>

<head>

<script language="JavaScript"><!--
function findLinkByHref(href) {
  for (var i=0; i<document.links.length; i++) {
    if (document.links[i].href == href) return i;
  }
  return -1;
}

function changeLinkHref(id,newHref,oldHref) {
  if (document.links.length > 0) {
    if (document.getElementById) {
      document.getElementById(id).href = newHref;
    }
    else if (document.all) {
      document.all[id].href = newHref;
    }
    else {
      var index = findLinkByHref(oldHref);
      if (index > -1)
        document.links[index].href = newHref;
    }
  }
}
//--></script>

</head>

<body>

<a id="myLink" href="http://www.mozilla.org">somewhere</a>

<form>
<input type="button" value="Change href" onClick="changeLinkHref('myLink','http://www.irt.org','http://www.mozilla.org')">
</form>

</body>

</html>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.