Home ยป JavaScript Sort Table By Column

JavaScript Sort Table By Column

JavaScript Sort Table By Column

JavaScript Sort Table By Column: JavaScript Sort Table By Column: In this article, we will learn how to sort an HTML table using Pure JavaScript, No plugins are required.

Basic HTML Structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Keyboard</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <!-- HTML code goes here -->
    <script src="app.js"></script>
</body>
</html>

HTML Code For Table Structure:

<div class="container">
  <input type="search" oninput="filter_table(this, 'table_filter')" class="form_control"
         placeholder="Filter This Table...">
  <table class="_table table_sort">
    <thead>
      <tr>
        <th>SL</th>
        <th>Name</th>
        <th>Phone</th>
        <th>Address</th>
        <th width="50px">Action</th>
      </tr>
    </thead>
    <tbody id="table_filter">
      <tr>
        <td>02</td>
        <td>Tamim</td>
        <td>+8801770 xxxxxx</td>
        <td>Address One</td>
        <td>
          <div class="action_btn">
            <a href="#" class="click_ripple_shine success" title="View">
              <i class="icon fa fa-eye"></i>
            </a>
            <a href="#" class="click_ripple_shine warning" title="Edit">
              <i class="icon fa fa-pencil-square-o"></i>
            </a>
            <a href="#" class="click_ripple_shine danger" title="Delete">
              <i class="icon fa fa-close"></i>
            </a>
          </div>
        </td>
      </tr>
      <tr>
        <td>01</td>
        <td>Khalid Hossain</td>
        <td>+8801770 xxxxxx</td>
        <td>Address Two</td>
        <td>
          <div class="action_btn">
            <a href="#" class="click_ripple_shine success" title="View">
              <i class="icon fa fa-eye"></i>
            </a>
            <a href="#" class="click_ripple_shine warning" title="Edit">
              <i class="icon fa fa-pencil-square-o"></i>
            </a>
            <a href="#" class="click_ripple_shine danger" title="Delete">
              <i class="icon fa fa-close"></i>
            </a>
          </div>
        </td>
      </tr>
      <tr>
        <td>03</td>
        <td>Sadik Hossain</td>
        <td>+8801770 xxxxxx</td>
        <td>Address Three</td>
        <td>
          <div class="action_btn">
            <a href="#" class="click_ripple_shine success" title="View">
              <i class="icon fa fa-eye"></i>
            </a>
            <a href="#" class="click_ripple_shine warning" title="Edit">
              <i class="icon fa fa-pencil-square-o"></i>
            </a>
            <a href="#" class="click_ripple_shine danger" title="Delete">
              <i class="icon fa fa-close"></i>
            </a>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>

<div class="container">
  <input type="search" oninput="filter_table(this, 'table_filter2')" class="form_control"
         placeholder="Filter This Table...">
  <table class="_table table_sort">
    <thead>
      <tr>
        <th>Company</th>
        <th>Contact</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody id="table_filter2">
      <tr>
        <td>Alfreds Futterkiste</td>
        <td>Maria Anders</td>
        <td>Germany</td>
      </tr>
      <tr>
        <td>Centro comercial Moctezuma</td>
        <td>Francisco Chang</td>
        <td>Mexico</td>
      </tr>
      <tr>
        <td>Ernst Handel</td>
        <td>Roland Mendel</td>
        <td>Austria</td>
      </tr>
      <tr>
        <td>Island Trading</td>
        <td>Helen Bennett</td>
        <td>UK</td>
      </tr>
      <tr>
        <td>Laughing Bacchus Winecellars</td>
        <td>Yoshi Tannamuri</td>
        <td>Canada</td>
      </tr>
      <tr>
        <td>Magazzini Alimentari Riuniti</td>
        <td>Giovanni Rovelli</td>
        <td>Italy</td>
      </tr>
    </tbody>
  </table>
</div>

CSS Code:

should I joined now, with students.* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
    font-family: Arial, Helvetica, sans-serif;
}

body {
    background-color: #efefef;
    padding: 25px;
}

.container {
    max-width: 900px;
    width: 100%;
    margin: 25px auto;
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 2px 20px #0001, 0 1px 6px #0001;
    border-radius: 5px;
    overflow-x: auto;
}

.form_control {
    border: 1px solid #0002;
    background-color: transparent;
    outline: none;
    padding: 8px 12px;
    width: 60%;
    color: #333;
    margin-bottom: 15px;
}

.form_control::placeholder {
    color: inherit;
    opacity: 0.5;
}

.form_control:is(:hover, :focus) {
    box-shadow: inset 0 1px 6px #0002;
    border-radius: 5px;
}

.success {
    background-color: #24b96f !important;
}

.warning {
    background-color: #ebba33 !important;
}

.primary {
    background-color: #259dff !important;
}

.secondery {
    background-color: #00bcd4 !important;
}

.danger {
    background-color: #ff5722 !important;
}


.action_btn {
    display: inline-flex;
    align-items: center;
}

.action_btn>* {
    border: none;
    outline: none;
    color: #fff;
    text-decoration: none;
    display: inline-block;
    padding: 8px 14px;
    position: relative;
    transition: 0.3s ease-in-out;
}

.action_btn>*+* {
    border-left: 1px solid #0003;
}

.action_btn>*:hover {
    filter: hue-rotate(-20deg) brightness(0.97);
    transform: scale(1.05);
    border-color: transparent;
    box-shadow: 0 2px 10px #0004;
    border-radius: 4px;
}

.action_btn>*:active {
    transform: scale(1);
    box-shadow: 0 2px 5px #0004;
}

._table {
    width: 100%;
    border-collapse: collapse;
}

._table :is(th, td) {
    border: 1px solid #0002;
    padding: 8px 10px;
}

._table th {
    position: relative;
    user-select: none;
}

._table th:hover {
    background-color: #0001;
    cursor: pointer;
}

._table th::after {
    content: '\25b4';
    position: absolute;
    right: 10px;
    font-size: inherit;
    transform-origin: center;
    transform: rotate(180deg);
}

._table th.asc {
    background-color: #0001;
}

._table th.asc::after {
    transform: rotate(0deg);
}

JavaScript Code:

let table_sort_elements = document.querySelectorAll('.table_sort');
if(table_sort_elements)
{
    table_sort_elements = Array.isArray(table_sort_elements) ? table_sort_elements : Object.values(table_sort_elements);
    table_sort_elements.forEach(table_sort_element=>{
        let thead_cells = table_sort_element.querySelectorAll('thead>tr>*');
        if(thead_cells)
        {
            thead_cells = Array.from(thead_cells);

            thead_cells.forEach((thead_cell, index)=>{
                thead_cell.addEventListener('click', function(){
                    this.classList.toggle('asc');
                    sortTableByColumn(table_sort_element, index, !this.classList.contains('asc'));
                });
            });
        }
    });
}


function sortTableByColumn(table, column, desc=false) 
{
    let tbody = table.querySelector('tbody'),
        rows  = tbody.querySelectorAll('tr');

    rows  = rows.isArray ? rows : Object.values(rows);

    function compare(a, b) {
        // console.log(a.children[column], b.children[column]);
        let aText = a.children[column].innerText.trim(),
            bText = b.children[column].innerText.trim();
        
        return (aText < bText) ? -1 : 1;
    }

    rows.sort(compare);

    if(desc) rows.reverse();

    tbody.innerHTML = '';

    let i = 0;
    while (i<rows.length) {
        tbody.appendChild(rows[i]);
        i++;
    }
}




/* html table filter javaScript code start */
function filter_table(This, table_id)
{
    let recordLists = document.querySelectorAll(`#${table_id}>*`);
    if(recordLists)
    {
        hide_tr(recordLists);
        recordLists.forEach(recordList=>{
            let str   = recordList.innerText.toLowerCase(),
                value = This.value.toLowerCase();

            if(str.indexOf(value)>=0)
            {
                recordList.style.display = '';
            }
        });
    }
}


function hide_tr(recordLists) {
    recordLists.forEach(recordList=>{
        recordList.style.display = 'none';
    });
}
/* html table filter javaScript code end */

Live Preview In Codepen:

CSS Keyboard | Create Keyboard Using HTML, CSS and JavaScript

Responsive HTML Table Design in CSS

Responsive HTML Table Design in CSS

Feel Free To Visit: Free Online Tools

My Youtube Channel Make Coding Easier

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock