JavaScript Form List Key to Index

JavaScript references list menu (dropdown) elements by their index number, not by the list menu's key. So if you want to preselect a list menu using JavaScript and you know they key in the key/value pairs that comprise the listmenu, here is a simple function I wrote which you pass the field id and the key you want the index for.

function key2index(field,value){
    for (i=0; i<$(field).options.length; i++){
        if ($(field).options[i].value == value) return i;
    } return 0;
}

  • Digg
  • TwitThis
  • del.icio.us
  • Netvouz
  • description
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank
  • Technorati
  • Facebook
  • Google
  • LinkedIn
  • Live
  • MySpace
  • Ping.fm
  • Yahoo! Buzz
  • E-mail this story to a friend!



Home | JavaScript | JavaScript Form List Key to Index