2

I am have a button like this:

<a class="btn btn-sm btn-danger employee" data-emp_id="23" href="javascript:void(0)" disabled>Resign</a>

If ajax response success it adds disabled to this button.

Here I need to this button has disabled on click event. If it has, need to alert different message, or if it hasn't I need to alert different message.

This is how I tried it.

$(document).on('click', 'a.employee', function(e){
  var empID  = $(this).data('emp_id');
  if($(this).is(':disabled')) {
    alert('message1');
  } else {
    alert('message2');
  }
});

Also tried it something like this:

$(document).on('click', 'a.employee:not(:disabled)', function(e){
  var empID  = $(this).data('emp_id');
  alert('here');
});

But, both are not working for me.. Hope somebody may help me out. Thank you.

0

2 Answers 2

1

You cannot disable an anchor element, and adding a disabled attribute to it would mean that your HTML is invalid.

To solve this you could simply add a class to the element and key the click behaviour on that. Try this:

$(document).on('click', 'a.employee', function(e) {
  e.preventDefault();
  var empID = $(this).data('emp_id');

  if ($(this).hasClass('disabled')) {
    console.log('message1');
  } else {
    console.log('message2');
  }
});
.disabled {
  color: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-sm btn-danger employee disabled" data-emp_id="23" href="#">Disabled</a>

<a class="btn btn-sm btn-danger employee" data-emp_id="23" href="#">Not disabled</a>

Also note the use of preventDefault() instead of adding javascript: to the href attribute of the a element.

2
  • Thank you for your answer. Can you tell me what is the wrong when using javascript:0 in href attribute of the a tag? Sep 16, 2016 at 9:38
  • It's ugly, outdated and not a good separation of concerns. If you place the preventDefault() in your JS code then all the JS is in a single place instead of being spread out over the project Sep 16, 2016 at 9:39
1

Disabled is not an attribute and hence not a property of anchor tag

try this way

$(document).on('click', 'a.employee[disabled])', function(e){
  var empID  = $(this).data('emp_id');
  alert('here');
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.