JavaScript to Sort Contents of Select Element

Javascript to sort contents of select element

This will do the trick. Just pass it your select element a la: document.getElementById('lstALL') when you need your list sorted.

function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}

how to sort select options based on values using pure Javascript?

Well, since you said you can't use jquery or can't modify java code. Here is a pure javascript solution. It would be better if you give an id for your select. You can save the options in an array and then use sort function by comparing first letter charcode of innerHTML inside each option.

in your HTML give an id

<html:select id="myselect" property="filterBookingTargetId" styleClass="input_middle" >
<html:option value="0">-all-</html:option>
<html:options collection="bookTargetTypes" property="key" labelProperty="value"/>
</html:select>

javascript

function sortOptions() {
var options = document.getElementById('myselect').options;
var optionsArray = [];
for (var i = 0; i < options.length; i++) {
optionsArray.push(options[i]);
}
optionsArray = optionsArray.sort(function (a, b) {
return a.innerHTML.toLowerCase().charCodeAt(0) - b.innerHTML.toLowerCase().charCodeAt(0);
});

for (var i = 0; i <= options.length; i++) {
options[i] = optionsArray[i];
}
options[0].selected = true;
}

sortOptions();

click here for Fiddle Demo

Sorting/reorganising a select option list in Javascript

You can use a function inside sort, in which you will sort the strings by some condition, in this case alphabetic order. It's used localCompare() built-in method to perform so.

Take a look:

const pattern = " - "
const chooseText = "Choose option"
const select = document.querySelector(".form-dropdown")

const children = [...select.children]

// brings "Out of stock" to the end
children.forEach(child => child.textContent = child.textContent.split(pattern).reverse().join(pattern))

children.sort(compareChild)

function compareChild(a, b){
const str_a = a.textContent
const str_b = b.textContent
// remember to not consider disabled option while sorting
if(str_a === chooseText || str_b === chooseText) return 0;
return str_a.localeCompare(str_b)
}

select.replaceChildren(...children)
<select class="form-dropdown">
<option disabled="" value="">Choose option</option>
<option value="6">Watermelon</option>
<option value="2">Out of stock - Cherry</option>
<option value="3">Kiwi</option>
<option value="0">Apple</option>
<option value="4">Out of stock - Lemon</option>
<option value="1">Banana</option>
<option value="5">Out of stock - Melon</option>
<option value="4">Out of stock - Pineapple</option>
<option value="1">Strawberry</option>
<option value="5">Out of stock - Khaki</option>
</select>

JavaScript - Sort SELECT options

Updated

You need to:

  • use a custom attribute for the dates
  • use sort() function's custom compare function parameter
  • convert to array to make sorting possible
  • convert the dates for string comparison (mm/dd/yyyy -> yyyy-mm-dd)

See it in action

[Tested on: IE 5.5+, FF 2+, Chrome 4+, Safari 4+, Opera 9.6+]

HTML:

<select name="sel_id" id="sel_id" size="4">
<option value="item2" date="02-01-2009">Item 2</option>
<option value="item3" date="01-05-2010">Item 3</option>
<option value="item1" date="10-06-2007">Item 1</option>
<option value="item4" date="04-05-2011">Item 4</option>
</select>

Javascript:

// array functions are not working
// on nodeLists on IE, we need to
// to convert them to array
function toArray( obj ) {
var i, arr = [];
for ( i = obj.length; i--; ){
arr[i] = obj[i];
}
return arr;
}

// custom compare function for sorting
// by the hidden date element
function sortByDate( el1, el2 ) {
var a = convertToDate( el1.getAttribute("date") ),
b = convertToDate( el2.getAttribute("date") );
if ( a < b ) return -1;
else if( a > b ) return 1;
else return 0;
}

// convert date for string comparison
function convertToDate( date ) {
date = date.split("-");
return date[2] + "-" + date[0] + "-" + date[1];
}

// select the elements to be ordered
var itemsId = document.getElementById("sel_id"),
items = itemsId.getElementsByTagName("option"),
len = items.length;

// convert to array, to make sorting possible
items = toArray( items );

// do the item sorting by their date
items = items.sort( sortByDate );

// append them back to the parent in order
for ( var i = 0; i < len; i++ ) {
itemsId.appendChild( items[i] );
}


How to sort a select element options with date value dd-mm-yyyy by month?

You can write date ticks instead of date. Its easy way. But if you have to use that format, you can check this link.

var opts = $("#date").find("option");
opts.sort(function(a,b){
if(a.innerHTML.indexOf("-") == -1)
return -1;
return getDate(a.innerHTML).getTime() > getDate(b.innerHTML).getTime() ? 1 : -1;
});
opts.each(function(x){
$("#date").append(this);
});

function getDate(strDate){
var parts = strDate.split('-');
return new Date(parseInt(parts[2]), parseInt(parts[1])-1, parseInt(parts[0]));
}

what is the correct way to sort list of items by using a select list

You can add a click event listener to all select options that loops through each li in the ul and hides those whose textContent is not equal to the textContent of the select option clicked.

const options = document.querySelectorAll('.dropdown .dropdown-content a')
const listItems = document.querySelectorAll('#list li');

options.forEach(f => f.addEventListener('click', function(e){
let text = this.textContent;
listItems.forEach(e => e.style.display = e.textContent == text ? "block" : "none")
}))
.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}

.dropdown {
position: relative;
display: inline-block;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}

.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}

.dropdown-content a:hover {
background-color: #ddd;
}

.dropdown:hover .dropdown-content {
display: block;
}

.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
<div class="dropdown">
<button class="dropSortbtn2"> Food <i class="bi bi-caret-down"></i></button>
<div class="dropdown-content">
<a href="#">Tomato</a>
<a href="#">APPle</a>
<a href="#">Carrot</a>
<a href="#">Broccoli</a>
</div>
</div>

<ul id="list">
<li>Tomato</li>
<li>APPle</li>
<li>Broccoli</li>
<li>Carrot</li>
<li>Tomato</li>
<li>Broccoli</li>
</ul>

Sorting options elements alphabetically using jQuery

What I'd do is:

  1. Extract the text and value of each <option> into an array of objects;
  2. Sort the array;
  3. Update the <option> elements with the array contents in order.

To do that with jQuery, you could do this:

var options = $('select.whatever option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});

Here is a working jsfiddle.

edit — If you want to sort such that you ignore alphabetic case, you can use the JavaScript .toUpperCase() or .toLowerCase() functions before comparing:

arr.sort(function(o1, o2) {
var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();

return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});

Sorting selectbox with Javascript

Here is working example.

    $(function() {
var select = $('select');
select.html(select.find('option').sort(function(x, y) {
var num1 = parseInt($(x).text());
var num2 = parseInt($(y).text());
return num1> num2 ? 1 : -1;
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="wrapper">
<select>
<option selected>Choose a number</option>
<option value="3">3</option>
<option value="1">1</option>
<option value="0">0</option>
<option value="2">2</option>
<option value="8">8</option>
</select>
</div>

What is the most efficient way to sort an Html Select's Options by value, while preserving the currently selected item?

Extract options into a temporary array, sort, then rebuild the list:

var my_options = $("#my_select option");
var selected = $("#my_select").val();

my_options.sort(function(a,b) {
if (a.text > b.text) return 1;
if (a.text < b.text) return -1;
return 0
})

$("#my_select").empty().append( my_options );
$("#my_select").val(selected);

Mozilla's sort documentation (specifically the compareFunction) and Wikipedia's Sorting Algorithm page are relevant.

If you want to make the sort case insensitive, replace text with text.toLowerCase()

The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the unicode collation algorithm). Using localeCompare in the sort function is a good solution, eg:

my_options.sort(function(a,b) {
return a.text.localeCompare(b.text);
});

Sort elements on page with selected option without using JQuery

First, you have to insert all articles into a div or any type of element you want.

Second, use classes of corresponding elements according to which you want to sort, as the value of select tag options. So according to your example we will use item_title, item_price as the values of select tag options.

Now see the full code, it will sort articles according to selected option, you will surely understand. I have shortened you articles for example.

function sort(sortBy) {  var items = document.getElementsByClassName("item_box");
// getElementsByClassName returns object. make it a array to use sort function var itemsArr = []; for (var i in items) { if (items[i].nodeType == 1) { // consider elements only itemsArr.push(items[i]); } }
var sorted = itemsArr.sort(function (a, b) { a = a.getElementsByClassName(sortBy)[0].innerHTML; b = b.getElementsByClassName(sortBy)[0].innerHTML; //decide whether need number sort or string sort if(isNaN(a) || isNaN(b)) return a.localeCompare(b); else return a-b; });
for (i = 0; i < sorted.length; ++i) { document.getElementById("items").appendChild(sorted[i]); }}
<div id="items">  <article class="item_box">    <p class="item_title">WIDGET 01</p>    <p class="amount"><span class="item_price">4232</span></p>  </article>  <article class="item_box">    <p class="item_title">WIDGET 02</p>    <p class="amount"><span class="item_price">4242</span></p>  </article>  <article class="item_box">    <p class="item_title">WIDGET 03</p>    <p class="amount"><span class="item_price">65</span></p>  </article>  <article class="item_box">    <p class="item_title">WIDGET 04</p>    <p class="amount"><span class="item_price">213</span></p></button>  </article><article class="item_box">  <p class="item_title">WIDGET 05</p>  <p class="amount"><span class="item_price">5321</span></p></article>  </div>
<p class="sort21">SORT BY:</p><select id="selectop" onchange="sort(this.value)"> <option value="item_title">NAME</option> <option value="item_price">COST</option></select>


Related Topics



Leave a reply



Submit