search

Home  >  Q&A  >  body text

Sorting HTML tables: a step-by-step guide

I'm not an HTML expert at all. I programmed the microcontroller and started going off on tangents.

I created an html document to display a table of microcontroller registers, register addresses, and register descriptions. I created a table with 3 columns and about 120 rows. Some register addresses are bit addressable - if their address ends with 0 or 8.

I want to highlight these "special" register addresses - by showing them in red. So, in the table cells where the register address ends with 0 or 8, I use "" and "" to surround the address value.

My table has 3 columns: register, address, and description. Then a line might look like

"ACC 0xE0 Accumulator".

I got the table all done and it looks great. Then it occurred to me that I wanted to be able to sort the table on any column. For example, if I click "Address" I want the table to redisplay and be sorted by the values ​​in that column.

I searched and found a way. How it works is that there is a "Sort" button - click that and it will redisplay the sorting of the first column values. I implemented a simple version of it and got it working. I then changed it to sort the second column when the "Sort" button is clicked.

This doesn't exactly work...because of all those ""s anyway.

Example I copied from him:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table

Is there something "simple" I can do to use this method - but still have some entries in the "Address" column appear red?

I should probably stick to programming microcontrollers, but I like a challenge.

P粉023326773P粉023326773430 days ago873

reply all(1)I'll reply

  • P粉676588738

    P粉6765887382023-11-01 09:19:09

    Sample code to sort selected columns,
    This is free...

    const
      myButtonSort  = document.querySelector('#my-button-sort')
    , colSelector   = document.querySelector('#sel-col')
    , myTable_tBody = document.querySelector('#my-table > tbody')
      ;
    myButtonSort.onclick = _ =>
      {
      let col = parseInt(colSelector.value ); 
      [...myTable_tBody.querySelectorAll('tr')]
        .map(row=>({row, str:row.cells[col].textContent }))
        .sort((a,b)=>a.str.localeCompare(b.str))
        .forEach(el=>
          {
          myTable_tBody.appendChild(el.row)
          })
      }
    table  {
      border-collapse : collapse;
      margin          : 2em 1em;
      }
    td,th  {
      padding    : .2em .8em;
      border     : 1px solid darkblue;
      }
    thead {
      background : lightseagreen ;
      }
    
    
    
    
    
    x y
    aa 1
    zz 2
    ee 3
    cc 4

    Ascending and descending sorting examples:

    const myArray = 
      [ { worth: '100',  name: 'jessca', reason: 'money', email: 'j@gmail.com',  number: '4456',  instagram: 'hvg_ujh', tiktok: 'hhgh.thg' } 
      , { worth: '265',  name: 'e',      reason: 'money', email: 'e@gmail.com',  number: '3456',  instagram: 'hvg_ujh', tiktok: 'hhgh.thg' } 
      , { worth: '6000', name: 'ssica',  reason: 'sex',   email: 's@gmail.com',  number: '0456',  instagram: 'hvg_ujh', tiktok: 'hhgh.thg' } 
      , { worth: '855',  name: 'sica',   reason: 'sex',   email: 'ss@gmail.com', number: '9456',  instagram: 'hvg_ujh', tiktok: 'hhgh.thg' } 
      , { worth: '8679', name: 'ica',    reason: 'sex',   email: 'i@gmail.com',  number: '0756',  instagram: 'hvg_ujh', tiktok: 'hhgh.thg' } 
      , { worth: '1',    name: 'ca',     reason: 'money', email: 'c@gmail.com',  number: '14856', instagram: 'hvg_ujh', tiktok: 'hhgh.thg' } 
      ] 
    const
      t_Head      = document.querySelector('#myTable thead')
    , t_Head_THs  = document.querySelectorAll('#myTable thead tr th')
    , th_list     = [...t_Head_THs].map( TH => TH.dataset.column)
    , t_Body      = document.querySelector('#myTable tbody')
    , sortOrder   = [ 'none' ,'asc', 'desc' ]
    , sortType    = { worth: 'num', name:'str', reason:'str', email:'str', number:'num', instagram:'str', tiktok:'str' }
    , sortProcess =
      { 'asc:num'  : (a,b) => +a.str - +b.str
      , 'desc:num' : (a,b) => +b.str - +a.str
      , 'asc:str'  : (a,b) => a.str.localeCompare(b.str)
      , 'desc:str' : (a,b) => b.str.localeCompare(a.str)
      };
    myArray.forEach( row =>
      {
      let TR = t_Body.insertRow()
      for (col of th_list)
        TR.insertCell().textContent = row[col] 
      })
    t_Head.onclick = ({target}) =>
      {
      if (!target.matches('th')) return
      
      let
        dataOrder = sortOrder[(sortOrder.indexOf(target.dataset.order) +1 )% sortOrder.length]
      , dataType  = sortType[target.dataset.column]
        ;
      t_Head_THs.forEach( TH => { TH.dataset.order = (TH===target) ? dataOrder : 'none' })
    
      if (dataOrder !== 'none')
        {
        [...t_Body.querySelectorAll('tr')]
        .map     ( row => ({row, str:row.cells[target.cellIndex].textContent }))
        .sort    ( sortProcess[`${dataOrder}:${dataType}`])
        .forEach ( elm => t_Body.appendChild(elm.row ))
        }
      }
    body { 
      font-family : Arial, Helvetica, sans-serif;
      font-size   : 16px;
      }
    table {
      border-collapse  : separate;
      border-spacing   : 1px;
      background-color : darkblue;
      margin           : 1em; 
      }
    th, td {
      border     : none;
      background : whitesmoke;
      padding    : .3em .4em;
      }
    th {
      background-color : #76ced1;
      white-space      : nowrap;
      cursor           : pointer;
      }
    th::before {
      content        : attr(data-column) ' ';
      text-transform : capitalize;
      }
    th[data-order=asc]::after  { content : 'B2'; }
    th[data-order=desc]::after { content : 'BC'; }
    th[data-order=none]::after { content : 'B2'; color:transparent; }  /* get the same width */

    reply
    0
  • Cancelreply