I think that selectedIndex will default to 0 if the selected attribute
is not set explicitly. The only workaround/hack I can think of is to
look at the innerHTML to see if it was set explicitly. Maybe something
like this:
jQuery("select").each(function(){
var thisSel = jQuery(this);
var oldVal = thisSel.val();
var setzero =
this.innerHTML.toLowerCase().indexOf('selected')
== -1 &&
this.selectedIndex==0;
thisSel.html(jQuery("option", this).sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));
if (setzero){
thisSel.attr("selectedIndex",0);
}else{
thisSel.val(oldVal);
}
});
Won't work on IE since it rewrites all of your option elements.
On Jan 17, 2:51 am, mdipierro <[email protected]> wrote:
> I would like to have all select/options automatically sorted client
> side. Tried this:
>
> <script>
> jQuery(document).ready(function(){
> jQuery("select").each(function(){
> var i = jQuery(this).attr('selectedIndex');
> jQuery(this).html(jQuery(this).children("option").sort(function
> (a,b) {
> return (a.text == b.text)?0:((a.text < b.text)?-1:1);
> }));
> alert(jQuery(this).attr('id')+i);
> if(i<0 || i==null)
> jQuery(this).children("option:first").attr("selected","selected");
> });});
>
> </script>
>
> <form>
> <select id="A">
> <option>C</option>
> <option selected="selected">B</option>
> <option>A</option>
> </select>
>
> <select id="C">
> <option>Z</option>
> <option>Y</option>
> <option>X</option>
> <option>T</option>
> </select>
> </form>
>
> The sorting works but while in the first case B is correctly selected.
> In the second case Z is selected instead of T.
> This is because if(i<0 || i==null) is always false while it should be
> true for the second select.
> Any idea of how to fix this?
>
> Massimo
--
You received this message because you are subscribed to the Google Groups
"web2py-users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/web2py?hl=en.