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.
5 Answers
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";
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 Comments
thirtydot
I think even jQuery might fail with
removeAtt :)alex
@thirtydot Whoops. I think I forgot an
r :)Solid1Snake1
This also works with document.getElementById(yourIdHere).removeAttribute('href');
with jQuery
if(!data){
$('#linkID').click(function(e) {
e.preventDefault();
});
}
with Prototype
if(!data){
$('linkID').observe('click', function(event) { event.stop() });
}
4 Comments
alex
Why not with another framework the OP didn't mention, such as MooTools? :P
alex
The point I was trying to make is that you answered with library code when the OP didn't specify a library.
Mithun Sreedharan
@alex yeah, i know to do it only with jQuery ;-)
Matt
Highest voted answer when the OP doesn't even mention jQuery... ridiculous.
<a href="javascript:check()">my link</a>
function check(){
var data =document.getElementById("yourdatafield").value;
if(data)
window.location="your_link_location";
}
2 Comments
Mithun Sreedharan
I wonder what will happen if data is null..
Anupam
@Mithun :we can check that in the if statement if required
With jQuery:
To disable:
$('#anchor_tag').attr("disabled", true);
To enable:
$('#anchor_tag').attr("disabled", false);
1 Comment
Rafael Herscovici
This wont work on Anchors.