Reputation: 709
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
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 td
s 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
<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>
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]);
});
I like this way better.
Source: http://jsfiddle.net/ZquQL/
Demo: http://jsfiddle.net/ZquQL/show
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