KBD

Keith Devens .com

Wednesday, October 15, 2008 Flag waving
A Lisp programmer knows the value of everything, but the cost of nothing. – Alan Perlis

Archive: June 29, 2007

← June 25, 2007July 03, 2007 →

Daily link icon Friday, June 29, 2007

<select> utility javascript functions

I always wind up needing functions to dynamically populate the options on a <select> list, or select a given item in an existing <select>. So I've finally written them out in a reusable form:

<select id="foo" onchange="alert(this.value)"/>

<script language="javascript" type="text/javascript">
function loadSelectOptions(selectId, keys, values, selectedOption){
    var list = document.getElementById(selectId)
    if(!list)
        return;

    var selectedIndex = 0;
    list.length = 0;

    var found = false;
    for(var i=0,n=keys.length; i<n; i++){
        list.options[i] = new Option(values[i], keys[i]);
        if(selectedOption == keys[i]){
            list.selectedIndex = i;
            found = true;
        }
    }
    return found;
}

function selectSelectOption(selectId, value, runEvent){
    var list = document.getElementById(selectId)
    if(!list)
        return;

    var options = list.options;
    for(var i=0,n=options.length; i<n; i++){
        if(options[i].value == value){
            list.selectedIndex = i;
            if(runEvent)
                list.onchange();
            return true;
        }
    }
    return false;
}

loadSelectOptions("foo",['foo','bar','baz'], ['FOO','BAR','BAZ'],'baz')
var list = document.getElementById("foo")
list.remove(1)
selectSelectOption("foo","baz")
</script>
← June 25, 2007July 03, 2007 →
October 2008
SunMonTueWedThuFriSat
 1234
567891011
12131415161718
19202122232425
262728293031 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 4 posts

Recent comments XML

new⇒Girls, please don't get breast implants

you people implants are fine these​days but they are like body organs​not e...

kym: Oct 15, 5:25pm

Spider solitaire

I have now won, at the "Difficult"​level, 186 games of Spider​Solitaire.  I...

75.179.28.113: Oct 13, 9:34am

I hate PHP

Elliot Anderson,

Dude!! You the​man! The reverse replacement for​array_u...

Alex Ndungu: Oct 11, 1:35am

Generated in about 0.049s.

(Used 7 db queries)

mobile phone