[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 469
  • Last Modified:

Disabling/Enabling links dynamically


The following function reads in the selected radio button and, according to its value, highlights the appropriate links.  Or rather actually greys out all the inappropriate ones.

I'd like to amend it so that it also disables the inappropriate ones so people can't click on them. But I can't do this permanently by removing the href or something because the links may need to be reenabled when someone chooses a different radio button.  

function showMyLinks(){
      var a = document.getElementById("linklist").getElementsByTagName("a");
//handle radio button
        var userType = document.forms.showlinks.showlinks;
        for(var i=0;i<userType.length;i++){
          if(userType[i].checked) sel = new RegExp("\\b"+userType[i].value+"\\b","i");
//add/replace one of the classes on each link to change its appearance to look disabled
        for(var i=0;i<a.length;i++){
      a[i].className += " all";  //one radio button is for all
          a[i].className = a[i].className.replace(" lowlight","");
                a[i].className += " lowlight";
3 Solutions
Eddie ShipmanAll-around developerCommented:
How about writing two onclick handlers, one of them doing nothing and assigning them at the
same time you do the class replacements?
YOu could put a div over each link. Would be transparent and prevent the user from clicking on it.

Here is an example.  I left the background blue to show you what it does.  It doesn't position correctly in IE, because IE doesn't take into account it's body margins/padding when you find an elements offset.  You may have to adjust that yourself.  You'd put this in your for loop

var disableDiv = document.createElement('div');
disableDiv.style.position = 'absolute';
disableDiv.style.width = a[i].offsetWidth + 'px';
disableDiv.style.height = a[i].offsetHeight + 'px';
disableDiv.style.left = a[i].offsetLeft + 'px';
disableDiv.style.top = a[i].offsetTop + 'px';
disableDiv.style.zIndex = 1000;
disableDiv.style.backgroundColor = 'blue';
Putting a DIV over each link will not prevent the user from using the keyboard.

You can cache the href value in the link:
  a.realHref = a.href;
  a.href = '#';

You can cancel the event like EddieShipman suggests:
  function cancelClick() {return false;}

  a.onclick = cancelClick;

To undo, just:
  a.onclick = null;


Lady_MAuthor Commented:
Okay thanks for that.  Sounds good, I'll give it a go hopefully at the end of the week and let you know how I get on.

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now