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..
-
1Based on what condition?Daniel Attfield– Daniel Attfield2012年08月10日 11:39:33 +00:00Commented Aug 10, 2012 at 11:39
-
From UX POV, users are hardly used to disabled links, so I'd recommend against it. If you need something disabled, it most likely should've been button.Oleg V. Volkov– Oleg V. Volkov2012年08月10日 11:43:21 +00:00Commented Aug 10, 2012 at 11:43
2 Answers 2
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";
}
2 Comments
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.