Newbie:Why can't I sort a Select.options[] array?

P

Patrick Nolan

I'm trying to write my first javascript. Here's the first
roadblock. I want to sort the order of the items in a
select object. Since they live in a Select.options[] array,
that ought to be possible. Yet when I try blah.blah.options.sort,
Firefox tells me that sort isn't a function. What's that about?
 
D

David Mark

I'm trying to write my first javascript. Here's the first
roadblock. I want to sort the order of the items in a
select object. Since they live in a Select.options[] array,
that ought to be possible. Yet when I try blah.blah.options.sort,
Firefox tells me that sort isn't a function. What's that about?

The options property is not an array. You can convert it to one with
Array.prototype.slice, as you can any array-like object. Of course,
sorting the resulting array won't do anything for the select element.
You would have to clear and re-populate it. You would really be
better off sorting the options server side.
 
R

Richard Maher

Hi Patrick,

Patrick Nolan said:
I'm trying to write my first javascript. Here's the first
roadblock. I want to sort the order of the items in a
select object. Since they live in a Select.options[] array,
that ought to be possible. Yet when I try blah.blah.options.sort,
Firefox tells me that sort isn't a function. What's that about?

Check out
http://groups.google.com/group/comp.lang.javascript/msg/fde4de8f56cf5c45 for
a similar case/question. Select.options[] is a collection rather than an
array, so apparently it has to be unloaded/sorted/reloaded. (Fine by me :)

Cheers Richard Maher

PS. If you want to see the example in action just let me know.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top