Nitara
Nitara

Reputation: 55

How to move all the rows of the table up in Javascript?

I want to shift all rows upward by calling a javascript function upward on button click. If my table has following contents:

1 2 3  
4 5 6  
7 8 9

then I want upward function to shift rows upward as follows while first row goes to last:

4 5 6  
7 8 9  
1 2 3  

Following is my javascript code:

<body>
<script>
    function display() {
        var table = document.createElement('table');

        table.setAttribute("id", "tbl");

        for (var i = 0; i < 4; i++) {
            var tr = document.createElement('tr');
            for (var j = 0; j < 4; j++) {
                var td = document.createElement('td');
                var text = document.createTextNode(j+i);

                td.appendChild(text);
                tr.appendChild(td);
            }
            table.appendChild(tr);
        }
        document.body.appendChild(table);
    }

        function upward() {
                var rows = document.getElementById('tbl').rows.length;
                for(var t=0;t< rows+1;t++)
                    {
                var row = document.getElementById("myTable").rows[t];
                row.insertBefore(row.prev());
                    }

        }
    </script>

        <input id="display" type="button" value="Display" onclick="display();" />
        <input id="upward" type="button" value="upward" onclick="upward();" />
</body>

Upvotes: 2

Views: 5361

Answers (2)

Lee Wise
Lee Wise

Reputation: 900

This can be done easily with jQuery. Basically remove the first row then re-insert it at the end.

function upward(table) {
	var firstRow = $('tr:first-child',table).remove();
  table.append(firstRow);
}

$(function() {
	$('#shift').on('click',function(){
  	upward($('table'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
<tr><td>7</td><td>8</td><td>9</td></tr>
</table>
<button id="shift">Shift</button>

Upvotes: 3

abdul khodir
abdul khodir

Reputation: 129

You Need to remove first element and then add it again. Try This :

function upward() {
  var table = document.getElementsByTagName('table');
  var table = table[0];
  var rows = table.getElementsByTagName('tr');
  var shifted = rows[0];
  rows[0].parentNode.removeChild(rows[0]);
  table.appendChild(shifted);
}
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
  <tr>
    <td>7</td>
    <td>8</td>
    <td>9</td>
  </tr>
</table>

<button onclick="upward()">Click!</button>

Upvotes: 7

Related Questions