You can prompt the code for sorting select'a alphabetically via JS. Googled custom sorting in JS, but all the time, it only produces an array sort. I can’t even begin with where to start, examples are zero, and I myself am not very far from JS. I would be very grateful for the help) Maybe someone already has a piece of code ready.
- oneAnd where does unsorted data appear in select? - Anton Shchyrov
- Due to some circumstances, they cannot be sorted on the server, I see no reason to describe long and tediously why, because this is not the question :) - D3V1L
- This is the question. Maybe you get them in JSON? And the impossibility of sorting on the server generally surprises me - Anton Shchyrov
|
2 answers
var sel = document.getElementById("x"); var arr = Array.from(sel.children).sort((x, y) => { return x.text.localeCompare(y.text); }); arr.forEach(x => sel.appendChild(x)); sel.selectedIndex = 0; <select id="x"> <option>вафля</option> <option>кафель</option> <option>арагок</option> <option>турок</option> <option>агент007</option> </select> - Thank you very much, it really works and is quite compact, tell another amateur how to make selectedIndex selected the very first, and then the list starts in the middle. - D3V1L
- @ D3V1L added. - Dmitry Polyanin
- Thank you very much. - D3V1L
|
let select = document.querySelector('select'); document.querySelector('#sortBtn').addEventListener('click', e => { sortIt((a, b) => a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()); }); document.querySelector('#revertSortBtn').addEventListener('click', e => { sortIt((a, b) => a.innerHTML.toLowerCase() < b.innerHTML.toLowerCase()); }); function sortIt(comparator){ [...select.children] .sort(comparator) .forEach(c => select.appendChild(c)); } <select> <option>Б</option> <option>А</option> <option>Г</option> <option>В</option> </select><br /><br /> <input type='button' id='sortBtn' value="Sort it!" /> | <input type='button' id='revertSortBtn' value="Revert sort it!" /> |