radbyx radbyx - 7 months ago 12
Javascript Question

Is :not(.disabled) always necessary for on eventhandlers?

Is there a way to get rid of

:not(.disabled)
in the eventhandler, for
li
that have
.disabled
, so "Do stuff" still happens?

I'm asking because I remember as I didn't had to add the
:not(.disabled)
to a button element or maybe it was a button acting like dropdown with
li a
elements inside.

HTML

<ul class="dropdown-menu">
<li id="fooId" class="disabled">
text
</li>
</ul>


JAVASCRIPT

$('body').on('click', '#fooId:not(.disabled)', function () {
// "Do stuff.."
});


UPDATE:

Boostrap dropdown li a disabled

Disabled menu items
Add .disabled to a
<li>
in the dropdown to disable the link.

<ul class="dropdown-menu" aria-labelledby="dropdownMenu4">
<li><a href="#">Regular link</a></li>
<li class="disabled"><a href="#">Disabled link</a></li>
<li><a href="#">Another link</a></li>
</ul>


I used this kind before, where
a
was included.

I was refactoring the code to another class and while I was at it, I removed
a
element too, and now I had to add
:not(.disabled)
to the eventhandler to not get in there for elements that are disabled as expected. But to my surprise, I guess it doesn't work if you remove the
a
element. (I have to test it again).

T J T J
Answer

If I understood correctly, what you want to do is:

$('body').on('click', 'li', function () {
  if($(this).hasClass('disabled'))
    return;  // Do stuff won't execute for disabled li, but will work for others
  // "Do stuff.."
});