I have to disable anchor link depending on a condition if some data comes to that field it should work as a hyperlink and if that data does not come then the link should not be there? Any ideas on this are welcome.
Asked
Active
Viewed 5.7k times
5 Answers
27
Case 1:
To disable:
document.getElementById(id).style.pointerEvents="none";
document.getElementById(id).style.cursor="default";
To enable:
document.getElementById(id).style.pointerEvents="auto";
document.getElementById(id).style.cursor="pointer";
Case 2:
If you want the link to be gone (not just disable it):
document.getElementById(id).style.display="none";
to get it back:
document.getElementById(id).style.display="block"; //change block to what you want.
Case 3:
If you want to hide it preserving the space for it:
document.getElementById(id).style.visibility="hidden";
To get it back:
document.getElementById(id).style.visibility="visible";
-
2This is nice because it works in cases where you have an href or an onclick. – MDM Jul 16 '18 at 18:18
-
you rock to the mx Jahin Saab. This is the only solution that worked for me. Would love if someone can explain why the prop(disable...) method doesn't work for anchors. – Desper Mar 18 '22 at 08:09
20
I couldn't make sense of your question body, so I'll answer your question's title...
How to disable anchor using javascript ?
JavaScript
if (condition) {
document.getElementsByTagName('a')[0].removeAttribute('href');
}
jQuery
...because everyone uses it, right?
if (condition) {
$('a').first().removeAttr('href');
}
-
3
-
1
-
2This also works with document.getElementById(_yourIdHere_).removeAttribute('href'); – Solid1Snake1 Oct 23 '17 at 22:15
3
with jQuery
if(!data){
$('#linkID').click(function(e) {
e.preventDefault();
});
}
with Prototype
if(!data){
$('linkID').observe('click', function(event) { event.stop() });
}

Mithun Sreedharan
- 49,883
- 70
- 181
- 236
-
2Why not with another framework the OP didn't mention, such as MooTools? :P – alex Apr 05 '11 at 13:52
-
1The point I was trying to make is that you answered with library code when the OP didn't specify a library. – alex Apr 05 '11 at 13:57
-
-
5Highest voted answer when the OP doesn't even mention jQuery... ridiculous. – Matt Apr 05 '11 at 14:02
1
<a href="javascript:check()">my link</a>
function check(){
var data =document.getElementById("yourdatafield").value;
if(data)
window.location="your_link_location";
}

Anupam
- 7,966
- 3
- 41
- 63
-4
With jQuery:
To disable:
$('#anchor_tag').attr("disabled", true);
To enable:
$('#anchor_tag').attr("disabled", false);

Jon Surrell
- 9,444
- 8
- 48
- 54

Maria
- 9
- 1