Sorting a table in html using only javascript - javascript

I'm trying to figure out how I can sort different columns in HTML. Right now, I have a button that sorts the first column (last name) in descending order. But now I'd like to create a second button, that sorts the 3rd column (Gender) by type.
Here is a link to what I currently have:
https://codepen.io/Pcollins10/pen/Wyxpyy
function sortTable() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("myTable");
switching = true;
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.getElementsByTagName("TR");
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < rows.length - 1; i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[0];
y = rows[i + 1].getElementsByTagName("TD")[0];
//check if the two rows should switch place:
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark that a switch has been done:*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
table {
border-spacing: 0;
width: 100%;
}
th, td {
text-align: left;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
<p><button onclick="sortTable()">Output 3 (Last Name..descending):</button></p>
<table id="myTable">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Birth Date</th>
<th>Favorite Color</th>
</tr>
<tr>
<td>Kournikova</td>
<td>Anna</td>
<td>Female</td>
<td>6/3/1975</td>
<td>Red</td>
</tr>
<tr>
<td>Hingis</td>
<td>Martina</td>
<td>Male</td>
<td>4/2/1979</td>
<td>Green</td>
</tr>
<tr>
<td>Seles</td>
<td>Monica</td>
<td>Female</td>
<td>12/2/1973</td>
<td>Black</td>
</tr>
<tr>
<td>Ambercrombie</td>
<td>Neil</td>
<td>Male</td>
<td>2/13/1943</td>
<td>Tan</td>
</tr>
<tr>
<td>Bishop</td>
<td>Timothy</td>
<td>Male</td>
<td>4/23/1967</td>
<td>Yellow</td>
</tr>
<tr>
<td>Kelly</td>
<td>Sue</td>
<td>Female</td>
<td>7/12/1959</td>
<td>Pink</td>
</tr>
<tr>
<td>Smith</td>
<td>Steve</td>
<td>Male</td>
<td>3/3/1985</td>
<td>Red</td>
</tr>
<tr>
<td>Bonk</td>
<td>Radek</td>
<td>Male</td>
<td>6/3/1975</td>
<td>Green</td>
</tr>
<tr>
<td>Bouillon</td>
<td>Francis</td>
<td>Male</td>
<td>6/3/1975</td>
<td>Blue</td>
</table>
]1
If possible, I'd like to be able to first sort by gender type, then (if the gender is the same), sort by last name.
See below for example.
Any advice would be greatly appreciated!

Related

Group column with the same subheader name in datatable using Javascript/jQuery

I have a table like this
In which I have different city where we have demand-supply of different products.
Now what I want as here demand is different for all the products However supply is the same on all of three product, so I want that table looks like in this manner.
What I want to do is I want only to show the supply column once in the last of the table. This has to be done dynamically as in the future we have multiple products
Can anyone help me with this?
What the code below does is:
Identify the positions of the "Supply"'s and store them in ind array, in this case will be [3, 5, 7]
Loops through ind except for the last element 7(as one "Supply" will be left) and hide all td's; $("td:nth-child("3"), $("td:nth-child("5")
The "Demand"s that precede each of these elements will be assigned two spaces.
let ind = [];
$("td:contains('Supply')").each(function (index) {
ind.push($(this).index() + 1);
});
$(".hide").on("click", function () {
for (let i = 0; i < ind.length - 1; i++) {
let el = $("td:nth-child(" + ind[i] + ")");
el.prev().attr("colspan", "2");
el.hide();
}
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>City</th>
<th colspan="2">Product 1</th>
<th colspan="2">Product 2</th>
<th colspan="2">Product 3</th>
</tr>
<tr>
<td></td>
<td>Demand</td>
<td>Supply</td>
<td>Demand</td>
<td>Supply</td>
<td>Demand</td>
<td>Supply</td>
</tr>
<tr>
<td>City 1</td>
<td>50$</td>
<td>60$</td>
<td>90$</td>
<td>60$</td>
<td>100$</td>
<td>60$</td>
</tr>
<tr>
<td>City 2</td>
<td>50$</td>
<td>60$</td>
<td>90$</td>
<td>60$</td>
<td>100$</td>
<td>60$</td>
</tr>
<tr>
<td>City 3</td>
<td>50$</td>
<td>60$</td>
<td>90$</td>
<td>60$</td>
<td>100$</td>
<td>60$</td>
</tr>
<tr>
<td>City 4</td>
<td>50$</td>
<td>60$</td>
<td>90$</td>
<td>60$</td>
<td>100$</td>
<td>60$</td>
</tr>
</table>
<button class="hide">Hide</button>

Sort a table with another table inside it

I currently have a table with a another table inside it that I have appended dynamically, for example:
<table>
<tr>
<th>Rank</th>
<th>Institute</th>
</tr>
<tr>
<td>1</td>
<td>MIT</td>
</tr>
<tr>
<td>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>David</td>
<td>21</td>
</tr>
<tr>
<td>James</td>
<td>19</td>
</tr>
</table>
</td>
</tr>
<td>2</td>
<td>UBC</td>
</tr>
<tr>
<td>
<table>
<tr>
<th>Age</th>
<th>Height</th>
</tr>
<tr>
<th>Angela</th>
<th>18</th>
</tr>
<tr>
<th>Peter</th>
<th>23</th>
</tr>
</table>
</td>
<tr>
I used a javascript table sorting function from w3schools and it works well:
function sortTable(tableId, valueType, column) {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById(tableId);
switching = true;
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].$("TD")[column];
console.log("x: " + x);
y = rows[i + 1].$("TD")[column];
if (valueType == "String") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (valueType == "Integer") {
if (parseInt(x.innerHTML.toLowerCase()) < parseInt(y.innerHTML.toLowerCase())) {
shouldSwitch = true;
break;
}
} else if (valueType == "IntegerReverse") {
if (parseInt(x.innerHTML.toLowerCase()) > parseInt(y.innerHTML.toLowerCase())) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
However, the problem is when I sort the table, the outer table sorts fine but the inner table gets messed up. I tried to give the inner table's parent td an id and tried to use the 'not' operator but I think because I am mixing jQuery with javascript, it still doesn't work.
Does anyone know how to sort just the outer table and keep the inner table as it is while still being appends to its parent td? Any help is much appreciated! ^^
Thank you!

Sort html table by columns with high, medium, low values using javascript

I am trying to sort a table using javascript but not in the traditional numerical or alphabetical sort method. Each Table row has 3 TD's. The first is the name second is a level (high, medium, low or blank) and the third is also a level (high, medium, low or blank). I am trying to sort the table based on the levels value , high, medium or low, and sending the empty TD's to the bottom.
I normally work with PHP so I am a little weak when it comes to javascript. Basics of what I am trying to do:
Count the number of tr's exclude the first one (Because its the header)
for each tr get the innerHTML of the second td. Compare each tds innerHTML and arrange them from High to low putting the empty ones last. If the header is clicked again reverse.
I think i pretty much have it worked out but I get stuck when it comes to switching the elements order.
<table id="myTable2">
<tr>
<th>Food/Beverage</th>
<th onclick="sortTable(1)">Alkalizing Level</th>
<th onclick="sortTable(2)">Acidic Level</th>
</tr>
<tr>
<td>Ale (Dark)</td>
<td></td>
<td>High</td>
</tr>
<tr>
<td>Ale (Pale)</td>
<td></td>
<td>High</td>
</tr>
<tr>
<td>Alkaline, Ionized Water</td>
<td>High</td>
<td></td>
</tr>
<tr>
<td>Almond Butter</td>
<td>Medium</td>
<td></td>
</tr>
<tr>
<td>Almond Milk (unsweetened)</td>
<td>Low</td>
<td></td>
</tr>
<tr>
<td>Almonds</td>
<td>Medium</td>
<td></td>
</tr>
<tr>
<td>Amaranth Seeds</td>
<td>Low</td>
<td></td>
</tr>
<tr>
<td>Apple Cider Vinegar</td>
<td></td>
<td>Low</td>
</tr>
<tr>
<td>Apple Juice</td>
<td></td>
<td>High</td>
</tr>
<tr>
<td>Apple Pie</td>
<td></td>
<td>High</td>
</tr>
<tr>
<td>Apples</td>
<td></td>
<td>Medium</td>
</tr>
<tr>
<td>Apricots</td>
<td></td>
<td>Medium</td>
</tr>
<tr>
<td>Apricots (Dried)</td>
<td></td>
<td>High</td>
</tr>
</table>
JS
<script>
table = document.getElementById("myTable2");
rows = table.rows;
i = 1;
count = 0;
while(i < rows.length){
alkLevel = rows[i].getElementsByTagName("TD")[1].innerHTML;
alkLevelNext = rows[i+1].getElementsByTagName("TD")[1].innerHTML;
var alkLevelPosition = 0;
i++;
if(alkLevel === "High"){
alkLevelPosition += 1;
}
if (alkLevel === "Medium"){
alkLevelPosition += 2;
}
if(alkLevel === "Low"){
alkLevelPosition += 3;
}
if(alkLevel === ""){
alkLevelPosition += 4;
}
if (alkLevelPosition > alkLevelNext) {
//shouldSwitch = true;
//break;
}
}
</script>
Here is an approach to getting the table sort you are looking for.
Added click event listeners to the table headers (rather than the inline onclick approach), then determined which column controls the sort using cellIndex, and included a sort function that handles the high, medium, low scoring properly.
Each time a header is clicked, all the table rows (except the header row) are removed, sorted, and then appended in the new order (added thead and tbody elements to simplify the selections) - in addition a class indicating the direction of the sort is added to the corresponding header element so that the next sort can be reversed.
Also, added alpha sort to the first table column as a bonus (just to simplify element selection and attaching the event listeners).
const headings = document.querySelectorAll('#myTable th');
const tbody = document.querySelector('#myTable tbody');
const sortRows = (order, i) => {
const rows = document.querySelectorAll('#myTable tbody tr');
if (i === 0) {
if (order === 'asc') {
return Array.from(rows).sort();
} else {
return Array.from(rows).sort().reverse();
}
} else {
return Array.from(rows).sort((a, b) => {
const aval = a.cells[i].textContent;
const bval = b.cells[i].textContent;
let s = 0;
if (aval === bval) {
s = 0;
} else if (aval === 'High') {
s = 1;
} else if (bval === 'High') {
s = -1;
} else if (aval === 'Medium') {
s = 1;
} else if (bval === 'Medium') {
s = -1;
} else if (aval === 'Low') {
s = 1;
} else if (bval === 'Low') {
s = -1;
}
if (order === 'desc') {
s *= -1;
}
return s;
});
}
};
for (const heading of headings) {
heading.addEventListener('click', (event) => {
const fragment = document.createDocumentFragment();
const elem = event.currentTarget;
let order = 'asc';
if (elem.classList.contains('asc')) {
order = 'desc';
elem.classList.remove('asc');
elem.classList.add('desc');
} else {
elem.classList.remove('desc');
elem.classList.add('asc');
}
for (const s of sortRows(order, elem.cellIndex)) {
fragment.appendChild(s);
}
while (tbody.firstChild) {
tbody.removeChild(tbody.firstChild);
}
tbody.appendChild(fragment);
});
}
th:hover {
cursor: pointer;
}
<table id="myTable">
<thead>
<tr>
<th>Food/Beverage</th>
<th>Alkalizing Level</th>
<th>Acidic Level</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ale (Dark)</td>
<td></td>
<td>High</td>
</tr>
<tr>
<td>Ale (Pale)</td>
<td></td>
<td>High</td>
</tr>
<tr>
<td>Alkaline, Ionized Water</td>
<td>High</td>
<td></td>
</tr>
<tr>
<td>Almond Butter</td>
<td>Medium</td>
<td></td>
</tr>
<tr>
<td>Almond Milk (unsweetened)</td>
<td>Low</td>
<td></td>
</tr>
<tr>
<td>Almonds</td>
<td>Medium</td>
<td></td>
</tr>
<tr>
<td>Amaranth Seeds</td>
<td>Low</td>
<td></td>
</tr>
<tr>
<td>Apple Cider Vinegar</td>
<td></td>
<td>Low</td>
</tr>
<tr>
<td>Apple Juice</td>
<td></td>
<td>High</td>
</tr>
<tr>
<td>Apple Pie</td>
<td></td>
<td>High</td>
</tr>
<tr>
<td>Apples</td>
<td></td>
<td>Medium</td>
</tr>
<tr>
<td>Apricots</td>
<td></td>
<td>Medium</td>
</tr>
<tr>
<td>Apricots (Dried)</td>
<td></td>
<td>High</td>
</tr>
</tbody>
</table>
So it sounds like you just need some help interacting with the DOM (Document Object Model). Looking at what you've written, it looks good so far, but you haven't done anything to actually change the order in which the tags are rendered.
There are numerous libraries that can do this for you, but I'll recommend doing a little bit of research into JavaScript yourself to learn how to actually manipulate the DOM (considering it's fundamental to what JavaScript does in the browser). As a hint, I'll suggest to break the task down into steps that the browser will need to perform:
Isolate the row object (everything between <tr></tr>) in memory from the DOM.
Remove the row object from the DOM.
Re-insert the row object into the DOM at the right place.
This link from W3Schools provides a good example of how to do exactly that: https://www.w3schools.com/howto/howto_js_sort_table.asp
They also have a number of tutorials and stuff that will help you build more proficiency in both HTML and JavaScript, and also CSS (which is really important for front-end stuff). Best of luck! Let us know if you have any questions!

Sort multiple tables with the same function using Javascript

I am trying to sort several tables using the same function within Javascript. The tables will all be similar, with me just wanting it to function that when you click on the table heading, it will sort alphabetically or in numerical order (highest to lowest), and when you click on the header again, it will sort that row in the reverse direction (e.g. lowest to highest).
I have used this code from W3 Schools: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table_desc
It works just fine for sorting just one table. However it doesn't work when I change 'GetElementById' to 'GetElementsByClassName'.
Below is my altered HTML code: Ignore the NFL content, as it's just data I'm using to test out the table contents)
<table border="1" class="supTable">
<tr>
<th onclick="sortTable(0)"> Team Name</th>
<th onclick="sortTable(1)">Super Bowls</th>
</tr>
<tr>
<td>Atlanta Falcons</td>
<td>0</td>
</tr>
<tr>
<td>Dallas Cowboys</td>
<td>4</td>
</tr>
<tr>
<td>Houston Texans</td>
<td>0</td>
</tr>
<tr>
<td>Green Bay Packers</td>
<td>3</td>
</tr>
<tr>
<td>New England Patriots</td>
<td>5</td>
</tr>
<tr>
<td>Oakland Raiders</td>
<td>2</td>
</tr>
<tr>
<td>New York Giants</td>
<td>2</td>
</tr>
<tr>
<td>Miami Dolphins</td>
<td>1</td>
</tr>
</table>
</div>
<div id="supAfc">
<table border="1" class="supTable">
<tr>
<th onclick="sortTable(0)"> Team Name</th>
<th onclick="sortTable(1)">Super Bowls</th>
</tr>
<tr>
<td>Houston Texans</td>
<td>0</td>
</tr>
<tr>
<td>New England Patriots</td>
<td>5</td>
</tr>
<tr>
<td>Oakland Raiders</td>
<td>2</td>
</tr>
<tr>
<td>Miami Dolphins</td>
<td>1</td>
</tr>
</table>
</div>
<div id="supNfc">
<table border="1" class="supTable">
<tr>
<th onclick="sortTable(0)"> Team Name</th>
<th onclick="sortTable(1)">Super Bowls</th>
</tr>
<tr>
<td>Atlanta Falcons</td>
<td>0</td>
</tr>
<tr>
<td>Dallas Cowboys</td>
<td>4</td>
</tr>
<tr>
<td>Green Bay Packers</td>
<td>3</td>
</tr>
<tr>
<td>New York Giants</td>
<td>2</td>
</tr>
</table>
</div>
And this is the Javascript code:
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementsByClassName("supTable");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.getElementsByTagName("TR");
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount ++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
I think I know why the class selector doesn't work, and am happy to try a different function if it gets me the results.
Can someone please help me using Javascript and ideally not jQuery, as I'm not familiar with jQuery at the moment.
I just want to be able to use the same function on several tables, so I'm not having to copy and paste the same code lots of times and changing the Id selector each time.
EDIT - A couple of people have mentioned a different question about Query selectors. How would I use query or class selectors to correctly call/solve my problem?
I haven't tested this out. Try it out and see if it works:
<table border="1" class="supTable1">
<tr>
<th onclick="sortTable('supTable1', 0)"> Team Name</th>
<th onclick="sortTable('supTable1', 1)">Super Bowls</th>
[...]
<div id="supAfc">
<table border="1" class="supTable2">
<tr>
<th onclick="sortTable('supTable2', 0)"> Team Name</th>
<th onclick="sortTable('supTable2', 1)">Super Bowls</th>
</tr>
And change the javascript function to:
function sortTable(tableClass, n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementsByClassName(tableClass)[0];
switching = true;
dir = "asc";
(I still don't understand why your post got downvoted in the first place)

Sorting HTML table by two columns

I have several columns in a table such as column A,B,C,D and E which I need to show in my HTML page. In some pages I need to show sorted results based on only one column of page, such as for Column "C" which is 3rd column of table. I am able to do this using the below code:
function Ascending(a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
var rows = $('#table tr').not(':first').get();
$('#table tr').slice(1).remove();
rows.sort(function(rowA, rowB) {
var keyA = $(rowA).children('td').eq(2).text().toUpperCase();
var keyB = $(rowB).children('td').eq(2).text().toUpperCase();
return Ascending(keyA, keyB);
});
But I have another requirement wherein I need to show the sorted results based on two columns i.e. based on the sorting of Column C in above case, results of column E should also get sorted. For example:
Before sorting:
Column C Column E
2 Fish
1 Box
7 Cat
2 Dog
1 Apple
2 Box
2 Axe
7 Box
2 Answer
7 Apple
6 Year
2 Goat
After sorting Column C only:
Column C Column E
1 Box
1 Apple
2 Dog
2 Fish
2 Box
2 Axe
2 Goat
2 Answer
6 Year
7 Box
7 Apple
7 Cat
After sorting Column C then Column E:
Column C Column E
1 Apple
1 Box
2 Answer
2 Axe
2 Box
2 Dog
2 Fish
2 Goat
6 Year
7 Apple
7 Box
7 Cat
Which I am unable to implement. How can I do it?
To sort by more than one column you write the comparison function like this:
(Comparison function is passed two "rows")
Compare row 1 column 1 with row 2 column 1
If they are different then return the result (a +ve or -ve number)
Compare row 1 column 2 with row 2 column 2
If they are different then return the result (a +ve or -ve number)
Repeat for remaining columns
Return 0
The following example shows how to write the compare function that sorts by two columns. It is possible to use a loop or recursion to sort by n columns.
$(function() {
function sortByColumn3(row1, row2) {
var v1, v2;
v1 = $(row1).find("td:eq(2)").text();
v2 = $(row2).find("td:eq(2)").text();
// for numbers you can simply return a-b instead of checking greater/smaller/equal
return v1 - v2;
}
function sortByColumn3And5(row1, row2) {
var v1, v2, r;
v1 = $(row1).find("td:eq(2)").text();
v2 = $(row2).find("td:eq(2)").text();
r = v1 - v2;
if (r === 0) {
// we have a tie in column 1 values, compare column 2 instead
v1 = $(row1).find("td:eq(4)").text();
v2 = $(row2).find("td:eq(4)").text();
if (v1 < v2) {
r = -1;
} else if (v1 > v2) {
r = 1;
} else {
r = 0;
}
}
return r;
}
$("#button1, #button2").on("click", function() {
var rows = $("#table1 tbody tr").detach().get();
switch (this.id) {
case "button1":
rows.sort(sortByColumn3);
break;
case "button2":
rows.sort(sortByColumn3And5);
break;
}
$("#table1 tbody").append(rows);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" id="button1" value="sortByColumn3">
<input type="button" id="button2" value="sortByColumn3And5">
<table id="table1" border="1" width="100%">
<thead>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</thead>
<tbody>
<tr>
<td>x</td>
<td>y</td>
<td>2</td>
<td>z</td>
<td>Fish</td>
</tr>
<tr>
<td>y</td>
<td>z</td>
<td>1</td>
<td>x</td>
<td>Box</td>
</tr>
<tr>
<td>z</td>
<td>x</td>
<td>7</td>
<td>y</td>
<td>Cat</td>
</tr>
<tr>
<td>x</td>
<td>y</td>
<td>2</td>
<td>z</td>
<td>Dog</td>
</tr>
<tr>
<td>y</td>
<td>z</td>
<td>1</td>
<td>x</td>
<td>Apple</td>
</tr>
<tr>
<td>z</td>
<td>x</td>
<td>2</td>
<td>y</td>
<td>Box</td>
</tr>
<tr>
<td>x</td>
<td>y</td>
<td>2</td>
<td>z</td>
<td>Axe</td>
</tr>
<tr>
<td>y</td>
<td>z</td>
<td>7</td>
<td>x</td>
<td>Box</td>
</tr>
<tr>
<td>z</td>
<td>x</td>
<td>2</td>
<td>y</td>
<td>Answer</td>
</tr>
<tr>
<td>x</td>
<td>y</td>
<td>7</td>
<td>z</td>
<td>Apple</td>
</tr>
<tr>
<td>y</td>
<td>z</td>
<td>6</td>
<td>x</td>
<td>Year</td>
</tr>
<tr>
<td>z</td>
<td>x</td>
<td>2</td>
<td>y</td>
<td>Goat</td>
</tr>
</tbody>
</table>
function sortTable() {
var table, rows, switching, i, x, y, a, b, shouldSwitch;
table = document.getElementById("mytable");
switching = true;
while (switching) {
switching = false;
rows = table.getElementsByTagName("TR");
for (i = 0; i < (rows.length - 1); i++) {
shouldSwitch = false;
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[3];
y = rows[i + 1].getElementsByTagName("TD")[3];
//check if the two rows should switch place:
if (Number(x.innerHTML) < Number(y.innerHTML)) {
//if so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switchcand mark that a switch has been done:*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
for (i = 0; i < (rows.length - 1); i++) {
/*Get the two elements you want to compare,one from current row and one from the next:*/
for (j = i + 1; j < (rows.length); j++) {
x = rows[i].getElementsByTagName("TD")[3];
y = rows[j].getElementsByTagName("TD")[3];
a = rows[i].getElementsByTagName("TD")[0];
b = rows[j].getElementsByTagName("TD")[0];
//check if the two rows should switch place:
if (Number(x.innerHTML) == Number(y.innerHTML)) {
//if so, swap
if (Number(a.innerHTML) > Number(b.innerHTML)) {
rows[i].parentNode.insertBefore(rows[j], rows[i]);
}
}
}
}
}
<body>
<div class="container">
<form class="form-horizontal" role="form">
<div class="form-group">
<button id="sort" onclick="sortTable()" type="button" class="btn btn-default">sort</button>
</div>
</form>
<div class="contents">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody id="mytable"><tr><td>5</td><td><img src="image/5.gif"></td><td>cony #5</td><td>170</td></tr><tr><td>1</td><td><img src="image/1.gif"></td><td>cony #1</td><td>170</td></tr><tr><td>2</td><td><img src="image/2.gif"></td><td>cony #2</td><td>270</td></tr><tr><td>8</td><td><img src="image/8.gif"></td><td>cony #8</td><td>70</td></tr><tr><td>10</td><td><img src="image/10.gif"></td><td>cony #10</td><td>170</td></tr><tr><td>4</td><td><img src="image/4.gif"></td><td>cony #4</td><td>150</td></tr><tr><td>3</td><td><img src="image/3.gif"></td><td>cony #3</td><td>130</td></tr><tr><td>6</td><td><img src="image/6.gif"></td><td>cony #6</td><td>160</td></tr><tr><td>9</td><td><img src="image/9.gif"></td><td>cony #9</td><td>170</td></tr><tr><td>7</td><td><img src="image/7.gif"></td><td>cony #7</td><td>170</td></tr></tbody>
</table>
</div>
</div>
</body>
Simple solution in Javascript
The above example is in descending order of price if same price column id will be in ascending order

Categories