Here’s a start for you.
Change your onclick
attributes to use .call()
. This just lets you set the value of this
in the functions you’re calling to the value of the first argument you pass to .call()
. (In this case, the element that received the event.)
<input type="button" name="Up1" value="Up" onclick="moveUp.call(this);"> Item 1
<input type="button" name="Down1" value="Down" onclick="moveDown.call(this);">
Then these functions should give a basic idea of how it could work. Probably could use some tweaks like making it so that you can’t add more rows than there are cells you’re sorting.
var table = document.getElementById( 'mytable' );
var filler = document.createElement( 'td' );
filler.className="filler";
filler.innerHTML = '*';
function moveUp() {
var cell = this.parentNode.parentNode;
var row = cell.parentNode;
var row_above;
if( row.rowIndex === 1 ) {
row_above = table.insertRow( 1 );
row_above.insertCell( 0 );
update_row_numbers();
} else {
row_above = table.rows[ row.rowIndex - 1 ];
}
if( row_above.cells[ 1 ] && row_above.cells[ 1 ].className === 'filler' ) {
row_above.removeChild( row_above.cells[ 1 ] );
}
row_above.appendChild( cell );
if( row.cells.length === 1 ) {
if( row.rowIndex < table.rows.length - 1 ) {
row.appendChild( filler.cloneNode( true ) );
} else {
table.deleteRow( table.rows.length - 1 );
update_row_numbers();
}
}
}
function moveDown() {
var cell = this.parentNode.parentNode;
var row = cell.parentNode;
var row_below;
if( row.rowIndex === table.rows.length - 1 ) {
row_below = table.insertRow( table.rows.length );
row_below.insertCell( 0 );
update_row_numbers();
} else {
row_below = table.rows[ row.rowIndex + 1 ];
}
if( row_below.cells[ 1 ] && row_below.cells[ 1 ].className === 'filler' ) {
row_below.removeChild( row_below.cells[ 1 ] );
}
row_below.appendChild( cell );
if( row.cells.length === 1 ) {
if( row.rowIndex > 1 ) {
row.appendChild( filler.cloneNode( true ) );
} else {
table.deleteRow( 1 );
update_row_numbers();
}
}
}
function update_row_numbers() {
for( var i = 1; i < table.rows.length; i++ ) {
table.rows[i].cells[0].innerHTML = i;
}
}
Live example: http://jsfiddle.net/v9ujy/3/
EDIT: Updated to prevent rows with the star from being at the beginning and end of the sorted rows.
2
solved Custom html table [closed]