The follwing code is to sort form list options alphabetically but the 'getElementsByClassName()' is not working and I cant figure out why.
I am using the latest jQuery.
window.onload=function(){
function sortlist() {
var cl = document.getElementsByClassName('car_options');
var clTexts = new Array();
for(i = 1; i < cl.length; i++) {
clTexts[i-1] =
cl.options[i].text.toUpperCase() + "," +
cl.options[i].text + "," +
cl.options[i].value;
}
clTexts.sort();
for(i = 1; i < cl.length; i++) {
var parts = clTexts[i-1].split(',');
cl.options[i].text = parts[1];
cl.options[i].value = parts[2];
}
sortlist();
}
in body section
<form action="" method="get">
<p><label for="car_make"></label>
<select id="car_make" class="car_options" name="car_make">
<option value="">By Make</option>
<option value="Vauxhall">Vauxhall</option>
<option value="BMW">BMW</option>
<option value="Toyota">Toyota</option>
<option value="Lexus">Lexus</option>
<option value="Audi">Audi</option>
<option value="Ford">Ford</option>
</select>
<label for="car_color"></label>
<select name="car_color" id="car_color" class="car_options">
<option value="">By Color</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Black">Black</option>
<option value="Grey">Grey</option>
</select>
<input type="submit" name="search" id="search" value="Search">
</form>
Use document.getElementsByClassName('car_options')[0]
getElementsByClassName
returns a set of elements which have all the given class names.
If you have multiple elements then we have to iterate it through. like
var elements = document.getElementsByClassName('car_options');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
}, false);
}
Note: In IE it is supported on IE9+
Updated Code
function sortlist() {
var elements = document.getElementsByClassName('car_options');
for (var j = 0; j < elements.length; j++) {
var cl = elements[j];
var clTexts = new Array();
for (i = 1; i < cl.options.length; i++) {
clTexts[i - 1] = cl.options[i].text.toUpperCase() + "," + cl.options[i].text + "," + cl.options[i].value;
}
clTexts.sort();
for (i = 1; i < cl.options.length; i++) {
var parts = clTexts[i - 1].split(',');
cl.options[i].text = parts[1];
cl.options[i].value = parts[2];
}
}
}
Working Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With