cssGEEK
cssGEEK

Reputation: 1014

tr won't be appended

I have an empty table which i want to fill with tds when i press a button.I want to create a new tr after every 3 tds. I have the following code:

var ruler=0;
    var start=false;
    $(document).ready(function(){
        $("button").on("click",function(){
            if (start === false){$("table").append("<tr>"); start = true;}
            if(ruler === 3){
                $("table").append("</tr><tr>");
                ruler = 0;
            }
            $("table tr").append("<td>mama</td>");
            ruler++;
        });
    });

html

 <table>
 </table>

The problem is that even after changing row it will continue adding tds in the first line.Any ideas?

Upvotes: 1

Views: 54

Answers (2)

mico
mico

Reputation: 12748

Use table tr:last as a selector to make sure for the application to append the content to the last row.

Upvotes: 1

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

As Teemu stated you are selecting all <tr>. So I added a :last selector.

    var ruler = 0;
    var start = false;
    $(document).ready(function() {
      $("button").on("click", function() {
        if (start === false) {
          $("table").append("<tr>");
          start = true;
        }
        if (ruler === 3) {
          $("table").append("</tr><tr>");
          ruler = 0;
        }
        $("table tr:last").append("<td>mama</td>");
        ruler++;
      });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button>Click me</button>
<table></table>

Upvotes: 2

Related Questions