In This Javascript Tutorial we will See How To Change Selected HTML Table Row Position Up Or Down On Button Click using JS And Netbeans Editor .
Subscribe : https://www.youtube.com/channel/UCS3W5vFugqi6QcsoAIHcMpw
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Row Up And Down</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
tr{cursor: pointer}
.selected{background-color: red; color: #fff;font-weight: bold}
button{margin-top:10px;background-color: #eee;border: 2px solid #00F;
color: #17bb1c;font-weight: bold;font-size: 25px;cursor: pointer}
</style>
</head>
<body>
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
<td>C2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
<td>C3</td>
</tr>
<tr>
<td>A4</td>
<td>B4</td>
<td>C4</td>
</tr>
<tr>
<td>A5</td>
<td>B5</td>
<td>C5</td>
</tr>
</table>
<button onclick="upNdown('up');">↑</button>
<button onclick="upNdown('down');">↓</button>
<script>
var index; // variable to set the selected row index
function getSelectedRow()
{
var table = document.getElementById("table");
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
// clear the selected from the previous selected row
// the first time index is undefined
if(typeof index !== "undefined"){
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction)
{
var rows = document.getElementById("table").rows,
parent = rows[index].parentNode;
if(direction === "up")
{
if(index > 1){
parent.insertBefore(rows[index],rows[index - 1]);
// when the row go up the index will be equal to index - 1
index--;
}
}
if(direction === "down")
{
if(index < rows.length -1){
parent.insertBefore(rows[index + 1],rows[index]);
// when the row go down the index will be equal to index + 1
index++;
}
}
}
</script>
</body>
</html>
#js #javascript