HTML Code
<Select id="alphalist">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</Select>
<div id="a" class="lists" style="display">
<ul id="alist">
<li>Axe</li>
<li>Arc</li>
<li>Apple</li>
</ul>
</div>
<div id="b" class="lists" style="display:none">
<ul id="blist">
<li>Bat</li>
<li>Boat</li>
<li>Bee</li>
</ul>
</div>
<div id="c" class="lists" style="display:none">
<ul id="clist">
<li>Cat</li>
<li>Coat</li>
<li>Clock</li>
</ul>
</div>
Script Code
$(function()
{
$('#alphalist').change(function(){
$('.lists').hide();
$('#' + $(this).val()).show();
});
});
Here I created 3 lists and a dropdown menu with options A,B and C. By default option A is selected and only the first list is displayed. Same way on clicking option B only second list is displayed and only third list is displayed when selecting option C. Now I need to sort each list in alphabetical order and display the sorted list corresponding to selected option.
Script code for sorting is:
var mylist = $('#alist');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
The above code sort only the first list. For sorting second list we need to write same above code again by replacing $('#alist) with $('#blist). So if we have, lets say, 20+ lists, how can we modify the above code so that we can sort all the available lists. If class name is common between all the lists, how sorting can be done? Please help me.