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";
Who is Participating?
LeeKowalkowskiConnect With a Mentor Commented:
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;


Eddie ShipmanConnect With a Mentor All-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?
MorcalavinConnect With a Mentor Commented:
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';
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.