pavan
pavan

Reputation: 451

How to disable the hyperlink based on the condition through Javascript

How to disable the hyperlink based on the condition

 var mydiv = document.getElementById("myDiv");      
 var aTag = document.createElement('a');       
 aTag.setAttribute('href',"yourlink.htm");        
 aTag.innerHTML = "link text";      
 mydiv.innerHTML="";      
 mydiv.innerHTML=aTag;  

say i need to disable my aTag here.

Based on logged on user i need to disable or enable..

Upvotes: 1

Views: 21927

Answers (2)

Tim M.
Tim M.

Reputation: 54387

You can disable the link by setting the disabled attribute (not valid on anchor elements, though it works in some cases).

Test setup for disabled attribute on anchors: http://jsfiddle.net/TgjnM/

Preferably, you can remove the link altogether and replace it with the text it contains. To replace the link with plain text, you would set the innerHTML of mydiv to the text (thus removing the hyperlink).

If the link can be toggled on/off, consider a form element (not a hyperlink) as @Oleg V. Volkov suggested in the comments. If it is a one-time decision (i.e. it won't be happening multiple times per page), I would replace the link with text.

Based on logged on user i need to disable or enable..

In that case, I would render the page differently on the server, not in the web browser.

Upvotes: 2

thecodejack
thecodejack

Reputation: 13379

This should work

 if(condition)
     disableLink();
else
   showLink();



function disableLink()
        {

        document.getElementById('Link1').disabled=true;
        document.getElementById('Link1').removeAttribute('href');    
        document.getElementById('Link1').style.textDecoration = 'none';
        document.getElementById('Link1').style.cursor = 'default';
        }

        function showLink()
        {
            document.getElementById('Link1').disabled=false;
        //assign href dynamically
        document.getElementById('Link1').href = "somepage.html";
        document.getElementById("Link1").style.textDecoration = "underline";
        document.getElementById("Link1").style.cursor = "hand";
        }

Upvotes: 2

Related Questions