Kiran Nunna
Kiran Nunna

Reputation: 158

How to enable/disable Anchor Tag

Below example is working for enable/disable of href but not for onclick. I need to enable/disable for both attributes

Note: I cant simply remove/bind the onclick event to dummy function() as it need once we enable it.

Script Code:

<script type="text/javascript">
 $(document).ready(function () {
     $("#b1").click(function () {
         $("#yahoo").attr("disabled", "disabled");
         $("#yahoo").css("background-color", "silver");
     })

     $("#b2").click(function () {
         $("#yahoo").removeAttr("disabled");
         $("#yahoo").css("background-color", "white");
     })

     $("#yahoo").click(function (e) {
         if ($("#yahoo").attr("disabled") == "disabled") {
             e.preventDefault();
         }
     });
 });
</script>

HTML Code:

 <div>
   <input type="button" id="b1" value="Disable Yahoo Link"> 
   <input type="button" id="b2" value="Enable Yahoo Link">    
 </div>    
 <a id="yahoo" target="_blank" href="javascript:alert('href alert')" onclick="javascript:alert('onclick alert')">Yahoo.com</a>

Working Example http://jsfiddle.net/nunnakirankumar/suYe4/

Upvotes: 0

Views: 22746

Answers (1)

parity3
parity3

Reputation: 703

Inside your click() function, you need to explicitly return false (after discovering it's disabled). Otherwise the default handler will cause the browser to go to or run the designated href.

The OP has most likely moved on, so this answer is really just for google searchers' sake.

Upvotes: 9

Related Questions