tjoenz
tjoenz

Reputation: 709

Moving values in cells within a table onclick of button

I'm trying to move cell values within a three by three table. But I am moving one cell at a time with the click of a button. Is this possible with jQuery or JS? I have the following table:

[1][2][3]
[4][5][6]
[7][8][9]

and I want to click a button to move right like so:

[4][1][2]
[7][5][3]
[8][9][6]

and so on..

this is my HTML:

<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="moveStuff">Move!</button>

Upvotes: 0

Views: 2444

Answers (1)

Joseph Marikle
Joseph Marikle

Reputation: 78530

This is so hacky and I don't necessarily advise it, but it should give you a place to start out from. Basically what you can do is create a function that grabs all the tds and based on their index value, rearrange them. Every time the function is called, it recreates the cells variable, meaning it will always start out fresh with the correct index values associated with the correct cells.

Source: http://jsfiddle.net/9nfvc/
Demo: http://jsfiddle.net/9nfvc/show

HTML

<table id="rotation">
  <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="moveStuff">Move!</button>

javascript

document.getElementById('moveStuff').onclick = (function(){
    var cells = document.getElementById('rotation').getElementsByTagName('td');
    var rows = document.getElementById('rotation').getElementsByTagName('tr');

    rows[2].appendChild(cells[5].parentNode.removeChild(cells[5]));
    rows[1].appendChild(cells[2].parentNode.removeChild(cells[2]));

    rows[1].insertBefore(cells[5].parentNode.removeChild(cells[5]), cells[3]);
    rows[0].insertBefore(cells[2].parentNode.removeChild(cells[2]), cells[0]);
});

EDIT

I like this way better.

Source: http://jsfiddle.net/ZquQL/
Demo: http://jsfiddle.net/ZquQL/show

javascript

document.getElementById('moveStuff').onclick = (function(){
    var parent = document.getElementById('rotation');
    var cells = [];
    var rows = parent.getElementsByTagName('tr');
    var patern = [3,0,1,6,4,2,7,8,5];

    for (var i = 0; i < rows.length; i++) {
        while(rows[i].firstChild) {
            var node = rows[i].removeChild(rows[i].firstChild)
            if(node.nodeType === document.ELEMENT_NODE) cells.push(node);
        }
    }

    row = -1;
    for(i in cells) {
        if(i%3 === 0) row++;
        rows[row].appendChild(cells[patern[i]]);
    }
});

Upvotes: 1

Related Questions