Thursday, February 10, 2011

How to retrieve a clicked element in a Jquery treeview

Hello,

I am willing to use the jquery treeview. I have categories and subcategories to choose for an item and I would like to display them in a treeview. I would like then to get the clicked value.

for the moment I am working on something of the kind of :

<ul id="treeview">
    <li>group1a
        <ul>
            <li>group11 </li>
        </ul>
    </li>
    <li>group2 </li>
    <li>group3 </li>
    <li>group4 </li>
    <li>group5 </li>
</ul>

and I tried this script, but the click function throw me an error.

<script type="text/javascript">
            $().ready(function () {
                $("#treeview").treeview();
            });

            $("#treeview").click(function (e) {
                e.target.addClass("selected");
            });

</script>

I am a very big beginner to this Jquery way of handling things, so I assume I am missing some important point somewhere... thanks for your help..

  • The addClass is an jQuery method, while e.target is not a jQuery object. You need to enclose it in $():

    $("#treeview").click(function (e) {
        $(e.target).addClass("selected");
    });
    

    Your code won't work anyways, as the click event is bound only to the #treeview element, and when that element fires, e.target will always be the #treeview element. What you're looking for is probably something like this:

    $("#treeview li").click(function() {
        $(this).addClass("selected");
    });
    

    This binds the click function to all li elements, and when one of them is clicked, it adds the "selected" class to that element.

    Probably you want to also allow deselecting of objects, so you should use toggleClass instead of addClass. If you want to allow selecting of only one object, you could use this:

    $("#treeview li").click(function() {
        // Clear all selected states
        $('#treeview li').removeClass('selected');
        // Set current as selected
        $(this).addClass("selected");
    });
    

    Hope this helps.

    fserb : I was in the middle of answering exactly this, but Tatu got it first.
  • Hi

    try:

    $(document).ready(function(){
        $("#browser").treeview({
            toggle:function(){
                console.log($(this).find('ul li'));
            }
        });
    

    Toggle is a callback for click. The 'this' value represents the 'li' that contains de 'ul' with the tree contents. In this case the console wills find all the 'li' nested inside 'ul'

    From returnvoid

0 comments:

Post a Comment