Clicking a button and detect its status in jquery

Question!

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.



Answers

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.



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');
});


There may be a chance of string value in the column RVU.MA. Try out with the below query to find out such descrepancies.

   SELECT *
   FROM RVU
   WHERE ISNUMERIC (RVU.MA)!=1


This video can help you solving your question :)
By: admin