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 |
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 :
<ul id="id01"> <li><span>Oslo</span></li> <li><span>tockholm</span></li> <li><span>Helsinki</span></li> <li><span>Berlin</span></li> <li><span>Rome</span></li> <li><span>Madrid</span></li> </ul>
Kodenya :
<script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script> $(document).ready(function(){ var list, i, switching, b, shouldSwitch; list = document.getElementById("id01"); 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; b = list.getElementsByTagName("li"); // Loop through all list-items: for (i = 0; i < (b.length - 1); i++) { // start by saying there should be no switching: shouldSwitch = false; /* check if the next item should switch place with the current item: */ if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) { /* if next item is alphabetically lower than current item, mark as a switch and break the loop: */ shouldSwitch = true; break; } } if (shouldSwitch) { /* If a switch has been marked, make the switch and mark the switch as done: */ b[i].parentNode.insertBefore(b[i + 1], b[i]); switching = true; } } }) </script>
Hore..... Done...