Cara Mengurutkan Data Di Dropdown Dengan Javascript

Tips Mengurutkan Data Di Dropdown Dengan Javascript

Ok tanpa BASI BASA keburu di kejar DEADLINE kita langsung aja ke TKP.

Cara Mengurutkan Data Di Dropdown Dengan Javascript
Cara Mengurutkan Data Di Dropdown Dengan Javascript
Dalam kasus ini kita akan mengurutkan data yang berada di dalam option select atau sering disebut dengan dropdown.

Tampilan Normal:

  • Oslo
  • tockholm
  • Helsinki
  • Berlin
  • Rome
  • Madrid

Setelah diurutkan:

  • Oslo
  • tockholm
  • Helsinki
  • Berlin
  • Rome
  • Madrid

Hal yang terbesit

Bagaimana Caranya ya kok bisa begitu ?


Kodenya HTML :

  1. <ul id="id01">
  2. <li><span>Oslo</span></li>
  3. <li><span>tockholm</span></li>
  4. <li><span>Helsinki</span></li>
  5. <li><span>Berlin</span></li>
  6. <li><span>Rome</span></li>
  7. <li><span>Madrid</span></li>
  8. </ul>

Kodenya :

  1. <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  2. <script>
  3. $(document).ready(function(){
  4. var list, i, switching, b, shouldSwitch;
  5. list = document.getElementById("id01");
  6. switching = true;
  7. /* Make a loop that will continue until
  8.   no switching has been done: */
  9. while (switching) {
  10. // start by saying: no switching is done:
  11. switching = false;
  12. b = list.getElementsByTagName("li");
  13. // Loop through all list-items:
  14. for (i = 0; i < (b.length - 1); i++) {
  15. // start by saying there should be no switching:
  16. shouldSwitch = false;
  17. /* check if the next item should
  18.   switch place with the current item: */
  19. if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
  20. /* if next item is alphabetically
  21.   lower than current item, mark as a switch
  22.   and break the loop: */
  23. shouldSwitch = true;
  24. break;
  25. }
  26. }
  27. if (shouldSwitch) {
  28. /* If a switch has been marked, make the switch
  29.   and mark the switch as done: */
  30. b[i].parentNode.insertBefore(b[i + 1], b[i]);
  31. switching = true;
  32. }
  33. }
  34. })
  35. </script>

Hore..... Done...
Previous Post
Next Post
Related Posts