0

I have a tree generated from database in apex 4.2:

<ul id="ltr">
<li id="00010" class="open"><a href="" style="" class=""><ins>&nbsp;</ins>Root</a>
<ul><li id="00110" class="open"><a href="" style="" class=""><ins>&nbsp;</ins>CHILD</a>
<ul><li id="00563" class="open"><a href="" style="" class=""><ins>&nbsp;</ins>CHILD</a>
<ul><li id="02057" class="leaf"><a href="" style="" class=""><ins>&nbsp;</ins>LAST CHILD</a></li>
</ul></li></ul>
</li>
</ul>
</li>
</ul>

I use a click function to select the id of a node, with class leaf no problem, but with open class selects the parent and the parent id, How Can I select the id of the node clicked ?

$(".leaf").click(function(){
        alert($(this).attr('id'));
    });


$(".open").click(function(){
        alert($(this).attr('id'));
    });

1 Answers1

1

You need to use stopPropagation(), otherwise your event listener will execute for all three nested elements when clicking the inner element. And you shouldn't use numbers as an ID.

Heres a working Fiddle:

$(document).ready(function(){
  $(".open").click(function(e){
    e.stopPropagation();
      alert($(this).attr("id"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul id="ltr">
  <li id="a00010" class="open">
    <a href="" style="" class=""><ins>&nbsp;</ins>Root</a>
      <ul>
        <li id="a00110" class="open"><a href="#"><ins>&nbsp</ins>CHILD</a>
          <ul>
            <li id="a00563" class="open"><a href="#"><ins>&nbsp;</ins>CHILD</a>
              <ul>
                <li id="a02057" class="leaf"><a href="#"><ins>&nbsp;</ins>LAST CHILD</a></li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
  </li>
</ul>

EDIT: If you want to select .open and .leaf just change the selector to:

$(".leaf, .open")
Marcel Dieterle
  • 335
  • 2
  • 6
  • Ok, it´s only a small example, but apex generate a big tree with numbers as ID, I only want to select the id of node clicked without selecting parent´s id – Alexander Orbes Sep 28 '16 at 20:57
  • My example will also work with IDs which are numbers. But it´s not recommended to do so since this can cause problems. See this post: http://stackoverflow.com/questions/5672903/can-i-have-a-div-with-id-as-number – Marcel Dieterle Sep 28 '16 at 21:00
  • Thanks it works perfectly, but how can I use that in dynamic action in apex 4.2 to control the tree selections. – Alexander Orbes Sep 28 '16 at 23:08