SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Jan 2007
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    <Select> - Finding the index based on the option value

    Hi,

    This is what I am trying to do:

    <Select name ="test">
    <option value="me">me</option>
    <option value="you">you</option>
    <option value="us">us</option>
    </Select>


    document.form.test.options[getIndexof('us')].selected = true;

    Coz I actually I want to do this:

    var value = r.select; //reading value from database.
    document.form.test.options[getIndexof(value)].selected = true;

    So basically, I pass the value of an option and find out the index for that option and make that index the selectedindex.

    Is there something already out there that can do it or do I have to write my own getIndxof(value)???

    Any help is appreciated. Thank you

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if its a single select (drop down) you can just do

    document.myform.test.value="you";

  3. #3
    SitePoint Member
    Join Date
    Jan 2007
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for reply.

    I already have this and it works fine in FF but doesn't work in IE 7 and that is why I am trying to find another way.

  4. #4
    SitePoint Addict jtrelfa's Avatar
    Join Date
    Oct 2004
    Location
    Troy, Mi
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ofarah View Post
    Is there something already out there that can do it or do I have to write my own getIndxof(value)
    I wish there was something like that, but there isn't. The only property directly related to 'index' is selectedIndex - which only gives you the one that's currently selected.

    You won't have to write a very complicated function, though: (untested)
    Code:
    function selectItem(elem,val) {
      var sel = document.forms[elem];
      for (var i = 0, len = sel.options.length; i < len; i++) {
        sel.options[i].selected = (sel.options[i].value == val);
      }
    }
    
    Somewhere in your code:
    selectItem('test','us');
    var me = null;


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •