Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap

Q916 How can I dynamically sort the options in a select form field?

You are here: irt.org | FAQ | JavaScript | Form | 4 | Q916 [ previous next ]

Only in JavaScript 1.1 or greater:

<script language="JavaScript"><!--
function sortOptions() {}

<script language="JavaScript1.1"><!--
function deleteOption(object,index) {
    object.options[index] = null;

function addOption(object,text,value) {
    var defaultSelected = false;
    var selected = false;
    var optionName = new Option(text, value, defaultSelected, selected)
    object.options[object.length] = optionName;
    object.options[object.length-1].selected = false;


function sortOptions(what) {
    var copyOption = new Array();
    for (var i=0;i<what.options.length;i++)
        copyOption[i] = new Array(what[i].value,what[i].text);

    copyOption.sort(function(a,b) { return a[0]-b[0]; });

    for (var i=what.options.length-1;i>-1;i--)

    for (var i=0;i<copyOption.length;i++)

<select name="selectName" multiple size="8">
<option value="8">apple
<option value="7">orange
<option value="6">pear
<option value="5">peach
<option value="4">banana
<option value="3">pineapple
<option value="2">cherry
<option value="1">grape

<input type="button" onClick="sortOptions(this.form.selectName)" value="Sort">


Feedback on 'Q916 How can I dynamically sort the options in a select form field?'

©2018 Martin Webb