jquery toggleClass() inside on() not working

293 Views Asked by At

This is my JQuery code, it (the class toggling) doesn't work..
I assume that it's the context of the this, but console.log() shows that it is the correct element.

// .dynamic-content AND ul are static. the event is delegated! 
$(".dynamic-content ul").on(
  'click',
  ".point_element",
  function(eve){
    $(this).css("border","2px solid green"); // works
    $(this).toggleClass("selected");         // not working
    $(this).prop("class","selected");        // works
    $("input", this).trigger('click');       // works
  }
);

The HTML:

<div class="dynamic-content">
<ul>
<li id="point_element_2877" class="element point_element">
  <fieldset><label><input value="po7" type="checkbox"></label></fieldset>
  <div class="inlined">
    <table>
      <tr><td>some text</td></tr>
    </table>
  </div>
</li>
...
...
2

There are 2 best solutions below

0
On BEST ANSWER

As @A.Wolff mentioned in his comment, the answer is that the code works just fine.
the problem is that the triggered event, is unchecking the element..

0
On

If your content is dynamically generated then you have to delegate the event to the closest static parent or document try below one:

$("staticParentID/Class").on('click', ".point_element", function (eve) { // static parent

or this one:

$(document).on('click', ".point_element", function (eve) { // delegated to document

Syntax is :

$(delegatedParent).on(event, selector, callbackFn);