user2320220
user2320220

Reputation: 7

unable to bind click event to nested li in jquery

I have done a lot but nothing is working anymore, i would like to do when i click on td then it will take the id of that td and this id will go to the database and it will fetch all the childs of that id. now i want to append those childs to that td based on id. But when i click on the nested td it take the id of parent. Here is my code.

<script type="text/javascript" >
$(document).ready(function() {
       var url = document.URL;
       var parts = url.split("/");
       var t = "";
       for(var i=0; i<parts.length-1; i++) {
            t += parts[i] + "/";
       }
       var which_li = "";
      $("td").bind('click',function(e) {
             e.stopPropagation();
             which_li = $(this).attr("id");

             $.ajax({   
                 type: "POST",
                 data : {id : which_li},
                 cache: false,  
                 url: t+"treeData",   
                 success: function(data){
                     var childs = data.split(",");
                     var res = "<table style='border:1px solid #ddd'><tr>";
                     for(var i=0; i<childs.length; i++ ){
                         if(childs[i] != "") {
                             res += "<td id='"+childs[i]+"'>"+childs[i]+"</td>";                                                         
                         }                                               
                     }
                     res += "</tr></table>"
                     $("td[id='" + which_li +"']").append(res);     
                 }
             }); 
      });   
});
</script>

Html table with default id that will be the root of all the id :

  <table id="data" style=" margin:0 auto; border:1px solid #ddd" >
    <tr>
         <td id='2'>2</td>
    </tr>
  </table>

it's working only once but after that it only taking the id of parent td not child td. Please help me to short out this problem.

e.stopPropagation();

Stop Propagation is also not working anymore.

here is my sql table

create table user_login (
        id int not null auto_increment,
        parent int not null
);

my table structure would be like this :

// this is my table strucutre
<table id="data" >
     <tr>  
          <td id="2">2
               <table>
                   <tr>
                       <td id="24">24
                             <table>
                                <tr>
                                    <td id="29">29</td>
                                    <td id="30">30</td>
                                </tr>
                             </table>
                       </td>
                       <td id="25">25</td>
                       <td id="26">26</td>
                   </tr>
               </table>
          </td>
     </tr>
</table>

when i will click on id 2 then a table will append to td containing childs 24,25,26 and when i will click on 24 then a table will append to td containing childs 29,30 and so on.

but when i want to get the id of 24 or 25 then it's giving me id of parent td that is 2 every time. Please help me.

Upvotes: 0

Views: 905

Answers (4)

Arthur
Arthur

Reputation: 1443

Well first of all, you are not binding the click event to newly added td's. Secondary, don't bind a click event to a tag, better give a class to a td, and bind the click to that class, this way you will have more flexibility. Corrected your code a bit:

<script type = "text/javascript" > 
    $(document).ready(function() {
        var url = document.URL;
        var parts = url.split("/");
        var t = "";
        for (var i = 0; i < parts.length - 1; i++) {
            t += parts[i] + "/";
        }
        var which_li = "";
        $("#data").on('click', '.closed', function(e) {
            var clicked_td = $(this);

            $.ajax({
                type: "POST",
                data: {
                    id: clicked_td.attr("id")
                },
                cache: false,
                url: t + "treeData",
                success: function(data) {
                    var childs = data.split(",");
                    var res = "<table style='border:1px solid #ddd'><tr>";
                    for (var i = 0; i < childs.length; i++) {
                        if (childs[i] != "") {
                            res += "<td class='.closed' id='" + childs[i] + "'>" + childs[i] + "</td>"; //added a 'closed' class
                        }
                    }
                    res += "</tr></table>"
                    clicked_td.removeClass("closed").append(res); //removing the class, so the click event won't fire again
                }
            });
        });
    }); 
</script>

And your html (added a class to td):

<table id="data" style=" margin:0 auto; border:1px solid #ddd" >
    <tr>
        <td id='2' class='closed'>2</td>
    </tr>
</table>

In the future, try to use dataType: 'json', and on your php side you can do something like:

...
$response = array('2', '3', '5', '10');
echo json_encode($response);

Using this method (and it is the right one if you takeajax seriously), you wond have to manually split the values, so instead of:

...
success: function(data) {
    var childs = data.split(",");
    var res = "<table style='border:1px solid #ddd'><tr>";
    for (var i = 0; i < childs.length; i++) {
        if (childs[i] != "") {
            res += "<td class='.closed' id='" + childs[i] + "'>" + childs[i] + "</td>";
        }
    }
    res += "</tr></table>"
    clicked_td.removeClass("closed").append(res);
}

You can do this:

success: function(data) {
    var res = "<table style='border:1px solid #ddd'><tr>";
    $each(data, function()
        res += "<td class='.closed' id='" + this + "'>" + this + "</td>";
    });
    res += "</tr></table>"
    clicked_td.removeClass("closed").append(res);
}

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388446

Try

$(document).ready(function() {
    var url = document.URL;
    var parts = url.split("/");
    var t = "";
    for(var i=0; i<parts.length-1; i++) {
        t += parts[i] + "/";
    }
    var which_li = "";
    $("#data td:not(.child td)").bind('click',function(e) {
        e.stopPropagation();
        var which_li = $(this).attr("id");

        $.ajax({   
            type: "POST",
            data : {id : which_li},
            cache: false,  
            url: t+"treeData",   
            success: function(data){
                var childs = data.split(",");
                var res = "<table class='child' style='border:1px solid #ddd'><tr>";
                for(var i=0; i<childs.length; i++ ){
                    if(childs[i] != "") {
                        res += "<td id='child-"+childs[i]+"'>"+childs[i]+"</td>";                                                         
                    }                                               
                }
                res += "</tr></table>"
                $("#" + which_li).append(res);     
            }
        }); 
    });   
});

Upvotes: 0

basarat
basarat

Reputation: 276393

Use live instead of bind if you want to bind to elements that might be added in the future since you are adding elements dynamically (http://api.jquery.com/live/) :

$(document).ready(function() {
       var url = document.URL;
       var parts = url.split("/");
       var t = "";
       for(var i=0; i<parts.length-1; i++) {
            t += parts[i] + "/";
       }
       var which_li = "";
      $("td").live('click',function(e) {
      // snip

Also stopPropogation works fine.

Upvotes: 0

dave
dave

Reputation: 64725

You are binding, but only to elements that exist when you bind. The event propagates up until it hits an element that was bound, at which point it is stopping propagation. What you need to do is bind the event to an element that exists, and then delegate that event to the one's that may or may not exist yet. Something like this should work:

 $("body").on('click', 'td', function(e) {
         e.stopPropagation();
         which_li = $(this).attr("id");

         $.ajax({   
             type: "POST",
             data : {id : which_li},
             cache: false,  
             url: t+"treeData",   
             success: function(data){
                 var childs = data.split(",");
                 var res = "<table style='border:1px solid #ddd'><tr>";
                 for(var i=0; i<childs.length; i++ ){
                     if(childs[i] != "") {
                         res += "<td id='"+childs[i]+"'>"+childs[i]+"</td>";                                                         
                     }                                               
                 }
                 res += "</tr></table>"
                 $("td[id='" + which_li +"']").append(res);     
             }
         }); 
  });   

Upvotes: 2

Related Questions