How to EASILY Sort HTML Tables with CSS & JavaScript - Web Development Tutorial

Поделиться
HTML-код
  • Опубликовано: 23 дек 2024

Комментарии • 122

  • @dcode-software
    @dcode-software  4 года назад +25

    IMPORTANT:
    If working with numerics, I recommend you parse your values to the correct type before comparisons for the most accurate results. For example, using "parseInt" or "parseFloat".
    This is especially important for floats, as you'll get bad results when sorting if they're represented as strings.

    • @krichter9245
      @krichter9245 4 года назад

      could you change it up in the Source Code that you linked? would really apreciate it because i can't make it work how it should.

    • @krichter9245
      @krichter9245 4 года назад

      Ok i made it work but now the name won't be sorted correctly..

    • @samuelhowell5962
      @samuelhowell5962 4 года назад +9

      @@krichter9245 you probably need to sort it differently based on the type of column, here's what I did:
      if (column !== 1) {
      sortedRows = rows.sort((a, b) => {
      const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
      const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();

      return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
      })
      }
      else {
      sortedRows = rows.sort((a, b) => {
      const aColPrice = parseFloat(a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));
      const bColPrice = parseFloat(b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));

      return aColPrice > bColPrice ? (1 * dirModifier) : (-1 * dirModifier);
      })
      }if (column !== 1) {
      sortedRows = rows.sort((a, b) => {
      const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
      const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();

      return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
      })
      }
      else {
      sortedRows = rows.sort((a, b) => {
      const aColPrice = parseFloat(a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));
      const bColPrice = parseFloat(b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));

      return aColPrice > bColPrice ? (1 * dirModifier) : (-1 * dirModifier);
      })
      }
      so basically I chekced to see if it was the column with numbers in it and sort differently based on that.
      one month late reply idk how useful this will be to you but good luck!

    • @meusingit2137
      @meusingit2137 4 года назад

      @@samuelhowell5962 Thanks Dude, Take care

    • @jaderzin
      @jaderzin 4 года назад

      @@samuelhowell5962 It was really useful to me. Thank you!!

  • @vitorpinto8110
    @vitorpinto8110 3 года назад +1

    Thanks bro. A big hug from Porto (Portugal).

  • @jtkw
    @jtkw 8 месяцев назад

    Thanks so much for this.! Is there a way to turn off the sorting capacity for a specific column (e.g.: the last column)?

  • @partygrouppl
    @partygrouppl 3 года назад +1

    its easy when you do it, applied and it works, but wouldnt figure out myself. Thanks a lot. Will make use of it for my ajax loaded tables.

  • @freizeitreiten
    @freizeitreiten 2 года назад +1

    great job, thx for showing!

  • @leonelcenteno3816
    @leonelcenteno3816 2 года назад

    So good, thank you. In my implentation, table are dynamically produced using AJAX calls. I linked the js at the top as if it were a CDN or something like that and it did not work. I solved it by adding the link to the js right after the script with the AJAX call, just in case someone else encounters a similar problem. Thanks again for this awesome tutorial.

  • @ankitdedhia8460
    @ankitdedhia8460 3 года назад

    It works so beautifully! Thanks Man!

  • @afonsopinto3418
    @afonsopinto3418 4 года назад +1

    Amazing!!! It helped a lot, It would be much cooler if the table heads add already the sorting icons and each time we clicked on the head cell the corresponding icon would turn to a different color, so people would know that the table is sortable. anyways 5 starts keep it up!!

  • @christianguerrero1110
    @christianguerrero1110 3 года назад

    Thank you for making a complex issue to me look easy!

  • @Makc199710
    @Makc199710 3 года назад +1

    Thank you it's the best lesson that I ever seen)))))

  • @Pedro-gu7jj
    @Pedro-gu7jj 3 года назад

    Bro, you resolve my problem , thanks for that! new sub

  • @nihilanz4097
    @nihilanz4097 2 года назад

    Thank you for this video. Very well done!

  • @michealkinney6205
    @michealkinney6205 2 года назад

    Very helpful reference. Thank you!

  • @mandeep_mehra
    @mandeep_mehra 4 года назад +2

    how can i use this without click mean , when load the page it automatically sort for first column ???

  • @AlvaroErnestoSanchezVega
    @AlvaroErnestoSanchezVega Год назад

    thank you very much, the code is super functional.

  • @hafizjavaid
    @hafizjavaid 4 года назад +2

    Thanks man for this information. Keep it up

  • @sandarateng785
    @sandarateng785 4 года назад +2

    Thanks mate! Keep it up!

  • @daedalusrasmus3278
    @daedalusrasmus3278 4 года назад +3

    I think there's a problem with case-sensitive entries, they seem to prioritize capitalized/upper-cased letters than lower-cased ones

  • @omar2013578
    @omar2013578 2 года назад +1

    thank >>>you can add toturial for multi filter table depend on html or javascript

  • @CaitlinFlynn-b3y
    @CaitlinFlynn-b3y Год назад

    Hello! I was wondering if you could tell me, how would you edit your table to only sort one column? I imagine it would be in headerCell function. Would you edit the tableElement variable? Or would it be in the document.querySelectorAll(".table-sortable th") part? Thank you so much if you could help me with this!

  • @maksimbronsky7117
    @maksimbronsky7117 4 года назад

    @dcode Why is that video part of the JavaScript Classes playlist?

  • @tradewinds9832
    @tradewinds9832 4 года назад

    Excellent mate. Thanks for sharing.

  • @ponedtonever
    @ponedtonever 2 года назад

    Thank you! This video helped me sort my table lol

  • @aurasolis9928
    @aurasolis9928 3 года назад

    Awesome video! I’m making a project and I want to do this but whit an input, so the client select the csv file and displays in the srcren

  • @kevinmorte3959
    @kevinmorte3959 3 года назад +2

    Very eloquent video, as usual. Just a quick question: instead of concatate .parentElement, would'nt be more effiicient to use .closes()? In that way, you don't have to previously be aware hay many levels there are from th to table. (and less code redundancy, maybe);
    Thanks for this videos, btw!

  • @zycro8084
    @zycro8084 3 года назад

    Thanks for the amazing tutorial, helped a lot!

  • @brianbrowni
    @brianbrowni 2 года назад

    do I have a possibility not to sort the Rank? let the rank fix?

  • @TownleyVM
    @TownleyVM Год назад

    So cool. Thank you. I got it to work with my php table as well and it works almost perfect. Sorting names, no problem, sorting numbers its a little fiddly though.

    • @michaelwang1524
      @michaelwang1524 Год назад +3

      hey idk if this helps you sort the numbers
      const sortedRows = rows.sort((a, b) => {
      const aColText = a.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
      const bColText = b.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
      const aNum = parseInt(aColText);
      const bNum = parseInt(bColText);
      return (aNum - bNum) > 0 ? (1 * dirModifier) : (-1 * dirModifier);
      });

    • @TownleyVM
      @TownleyVM Год назад

      @@michaelwang1524 Thank you so much. That totally worked. Greatly appreciated.

    • @michaelwang1524
      @michaelwang1524 Год назад

      @@TownleyVM You know what we should totally work together if ur also building a website so we can bounce ideas off of each other.

    • @lachlanpirie899
      @lachlanpirie899 Год назад

      @@michaelwang1524 I had this problem too and this sorted it, thank you! My first column is made up of strings and the rest numbers so I added an if statement to differentiate between your return code and the one used in the video.

  • @minnuss
    @minnuss 2 года назад

    Great code !!
    I managed to solve the problem with better sorting of numbers, and add some code that can detect if the table is with numbers or letters.

    • @d0gg087
      @d0gg087 2 года назад

      please share

  • @ryrilya2289
    @ryrilya2289 3 года назад

    This was very useful, thanks a lot!

  • @jeslyndanielleella408
    @jeslyndanielleella408 9 месяцев назад

    Hello, I'm using this code and it works very well. However, when I use it on paginated tables, it will only sort the rows found on the current page. I want it to sort all the rows. Please help.

  • @geethac2707
    @geethac2707 3 года назад

    Awesome video! How do you make it sort selected values from a dropdown column? Thanks!!

  • @James-ml5mu
    @James-ml5mu 3 года назад

    Thank you for this video!

  • @miltont5173
    @miltont5173 3 года назад +1

    Awesome work, is it possible to filter on the name column?
    Would you consider doing a follow-up video on how to do this if possible please?

  • @VIDEORealism
    @VIDEORealism 10 месяцев назад

    great video for a complete .js noob like me even though it didn't work for me and I don't not finde the mistake I made, so I had to copy your script from code pen... at least I tried XD Im wondering how to put the table back in the original sequence as it was before sorting without reloading the site? the tables at wikipedia for example do have this 3 states for each column - asc, desc and back to original...

  • @summaalchemica364
    @summaalchemica364 Год назад

    Awesome, thanks

  • @mohammedkalim7642
    @mohammedkalim7642 3 года назад

    Really amazing and thanks for making this

  • @Mo-po3gh
    @Mo-po3gh 2 года назад

    you are awesome dude

  • @Pyraptor
    @Pyraptor 4 года назад +2

    Thanks! I'm tired of using CSS libraries

  • @swathikrishnan3956
    @swathikrishnan3956 2 года назад

    How to increase size of that sort arrow

  • @henrychoy7342
    @henrychoy7342 4 года назад

    Thanks fort this! But the code doesn't seem to work if the table is populated with AJAX?

  • @TriinTamburiin
    @TriinTamburiin 3 года назад +5

    Instead of traversing DOM one by one like:
    const tableElement = headerCell.parentElement.parentElement.parentElement;
    It's easier just to use closest() method.
    const tableElement = headerCell.closest('.table');

    • @dcode-software
      @dcode-software  3 года назад +1

      That's a much better solution. I've been using it in my recent videos. Thanks 😀

  • @ANDREANEVE-r3z
    @ANDREANEVE-r3z Год назад

    thanks it works great

  • @jaafaryusuf1444
    @jaafaryusuf1444 4 года назад

    Hello, what if I want to work with table that requires calculations?

  • @yorker3148
    @yorker3148 2 года назад

    thanks ! very helpful

  • @hazara4831
    @hazara4831 2 года назад

    How can I do pagination?

  • @jdubhman
    @jdubhman 3 года назад

    Cheers mate 🍻

  • @jaderzin
    @jaderzin 4 года назад

    Do I have to change anything to make this work with flask? Mine isn't working. Nothing happens =(

  • @markreeves5561
    @markreeves5561 4 года назад +1

    Thanks for the tutorial. It's great. It Just helped me in my project

  • @rafaelefstathiou7516
    @rafaelefstathiou7516 4 года назад +1

    Great help and amazing explanation! The question is how can i do this beautiful sorting you did using DropDown menus and Select Tags?

  • @abanwaraphael1526
    @abanwaraphael1526 2 года назад

    Great video but Does this work on pagination?

  • @Usernameiswadum
    @Usernameiswadum 4 года назад +1

    Thank you so much! :)

  • @swara_dange09
    @swara_dange09 3 года назад

    how to sort table column based on dropdown option

  • @nicolebenedictlim9393
    @nicolebenedictlim9393 4 года назад +1

    Thanks for sharing this will help a lot for my current project , but there's a line of code that I cannot understand please see below:
    return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
    what does this code mean ? thanks !

    • @dcode-software
      @dcode-software  4 года назад +3

      It's using the ternary operator: developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
      We want either -1 or 1, and the dirModifier flips number (-1 or 1) depending on if we are sorting ascending or descending

    • @nicolebenedictlim9393
      @nicolebenedictlim9393 4 года назад

      @@dcode-software thank you sir

  • @ktr66
    @ktr66 3 года назад +1

    Thanks for posting this tutorial, it is fantastic! What part o the code would I change to have the first column click present the descending order?

    • @ktr66
      @ktr66 3 года назад +1

      Thanks again for great video and code. I figured it out. I set the 'asc' parameter to 'false' in the sortTableByColumn function and also named the const dirModifier = asc ? from 1 : -1 to -1 : 1

  • @MrFyce
    @MrFyce 3 года назад

    how to integrate this with mysql?

  • @emmanuellefrappier4651
    @emmanuellefrappier4651 4 года назад

    if i don't want to sort all the columns, what should i change please?

  • @slavicakaraterzieva3257
    @slavicakaraterzieva3257 4 года назад

    I get error in declaring the constants, like: sortedRows is declared but it's value is never read. I'm all day on it trying to solve it. I'm using visual studio 2017. Help please anybody?

  • @KilconL
    @KilconL 3 года назад

    Clicked subs and love you

  • @sirmonke
    @sirmonke 4 года назад

    can i also sort certain categories(dates dont function)

    • @vidhyas806
      @vidhyas806 3 года назад

      did u get the solution?

  • @investontech3916
    @investontech3916 3 года назад

    when i try inspect its working but its not sorting. need help please

  • @רותיכהן-מ7ר
    @רותיכהן-מ7ר 3 года назад

    You are awesomeeeeeeeeeeeeeee!!!! thx

  • @Rrs774
    @Rrs774 4 года назад

    How can you keep the ranking order unchanged ?

    • @dcode-software
      @dcode-software  4 года назад

      You could make use of something like Local Storage or Session Storage

    • @Rrs774
      @Rrs774 4 года назад

      I made it work with a forEach on every row to keep the index before adding to the empty table...thank you for the quick reply:D

  • @kasvith
    @kasvith 4 года назад

    Can you do this with Vue? would be awesome

  • @yumincao9209
    @yumincao9209 3 года назад

    Thank you!!! :-D

  • @tarunpatel1827
    @tarunpatel1827 3 года назад

    Great tutorial thanks!!
    Can you also do a tutorial on pagination

  • @demodemo-q8l
    @demodemo-q8l Год назад

    not working in paginations

  • @AndriusAndrulionis
    @AndriusAndrulionis 4 года назад +1

    If numbers are more than 10 it sorting 1 10 11 2 3 4... or 9...3 2 11 10 1 it's ok if writing 01 02 03... :)

  • @skiiiworld6205
    @skiiiworld6205 Год назад

    everything works for me but not the CSS i dont know why anyone having issue applying css arrows doesnot appear?

  • @michaelwang1524
    @michaelwang1524 Год назад +1

    Sort by numbers only
    const sortedRows = rows.sort((a, b) => {
    const aColText = a.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
    const bColText = b.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
    const aNum = parseInt(aColText);
    const bNum = parseInt(bColText);
    return (aNum - bNum) > 0 ? (1 * dirModifier) : (-1 * dirModifier);
    });

  • @petco605
    @petco605 Год назад

    I followed the video and my sorting doesnt work :(

  • @Nice4Nice
    @Nice4Nice 3 года назад

    Great

  • @powerstar61
    @powerstar61 2 года назад

    Bro, please share code

  • @ninam7749
    @ninam7749 2 года назад

    🙏🏽🙏🏽🙏🏽

  • @ilovecoffee7623
    @ilovecoffee7623 3 года назад +5

    Why are you using such a convoluted and complex way of getting the index of each clicked 'TH', when you can just use the 'index' argument of forEach() instead? Instead of this: const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell), you can just pass 'index' argument, and then assign it to headerIndex.

    • @powerstar61
      @powerstar61 2 года назад

      Hi,
      Can you share full code please

  • @homeChannel2000
    @homeChannel2000 2 года назад +1

    Thank you so very much. For this beautiful tutorial :)

  • @designwithdiv
    @designwithdiv 3 года назад

    How to pagination with it?