0

since I am new to JS / jQuery it is probably a obvious problem (but no exception thrown). I read that I can't use .onclick so i tried this approach with .on("click"...)

I try to build a table that adds new lines under the clicked line. This should also work for the newly created lines.

My html:

<tbody>
    <tr id="line1"><td>Stuff1</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>
    <tr id="line2"><td>Stuff2</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>
    <tr id="line3"><td>Stuff3</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>
    <tr id="line4"><td>Stuff4</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>
</tbody>

My JS:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 

<script>    

    $(document).ready(function(){ 
        $("tr").on("click",function(){
            var childId = $(this).attr("id")+1;
            if($("#"+childId).length){
                $("#"+childId).toggle();
            }else{
                $(this).after('<tr id="'+childId+'"><td>Stuffxxxx</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>');
                //AJAX
            }
        });
    }); 
</script>

Thanks for your help! :)

Simon
  • 5
  • 1
  • 3

1 Answers1

0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 

<script>    

    $(document).ready(function(){ 
        $("table").on("click","tr", function(){
            var childId = $(this).attr("id")+1;
            if($("#"+childId).length){
                $("#"+childId).toggle();
            }else{
                $(this).after('<tr id="'+childId+'"><td>Stuffxxxx</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>');
                //AJAX
            }
        });
    }); 
</script>
Mohit Bhardwaj
  • 9,650
  • 3
  • 37
  • 64