ok, so I have this code:
$(function(){
// TODO make this work
$('select#selList').change(function(){
if($(this).val()=="alpha"||$(this).val()=="date"|$(this).val()=="nil")
$selectedValue=0;
else
$selectedValue=$(':selected').val();
$options=$('#selList').children('option');
$arrVals=[];
$options.each(function({
if($(this).val()=="alpha"||$(this).val()=="date"|$(this).val()=="nil")
{
return true;
}
else
{
$arrVals.push({
valx:$(this).val(),
txtx:$(this).text(),
datex:$(this).attr('date')
});
}
});
var sort_by = function(field, reverse, primer)
{
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return ((A < B ? -1 :(A > B) ? +1 : 0)) * [-1,1][+!!reverse];
}
}
switch($(':selected').attr('id'))
{
case 'alpha':
$arrVals.sort(sort_by('txtx',true,false));
break;
case 'date':
$arrVals.sort(sort_by('datex',true,false));
break;
}
$(this).html("");
for(var i=0, m=$arrVals.length;i<m;i++)
{
$($options[i]).text($arrVals[i].txtx);
$(this).append($options[i]);
}
$(this).append('<option value="nil" id="nil">---------------------------</option><option value="alpha" id="alpha">Sort alphabeticaly</option><option value="date" id="date">Sort by date</option>')
$(this).val($selectedValue);
});
});
Now all I want is to store the selected option if it defers from the “—-“, “Sort alphabeticaly” and “Sort by date” option, and keep it selected now matter what my succesive clicks are and the order of the options in the list.
The HTML is as follows:
<select id="selList" multiple style="height:150px">
<option value="1" date="20120126">A</option>
<option value="2" date="20120124">D</option>
<option value="3" date="20120125">B</option>
<option value="4" date="20120129">C</option>
<option value="nil" id="nil">---------------------------</option>
<option value="alpha" id="alpha">Sort alphabeticaly</option>
<option value="date" id="date">Sort by date</option>
</select>
Thanks for your help 🙂
Give it a try:(you may prepend the function-body to your existing function)
Onchange it collects all selected options that have a numeric value. If there are any, it stores this collection as data inside the select.