HTML Dropdown boxes

Discussion in 'JavaScript' started by NoamBarz, Jun 7, 2007.

  1. #1
    I'm using an HTML dropdown box like this:

    <select name="bla">
    <option value='1'>aaa</option>
    <option value='2'>bbb</option>
    <option value='3'>ccc</option>
    </select>

    if I want to get the selected option's value, I use something like this:

    document.frm.bla.value;

    What I would like to know is whether there is a way to retrieve the text associated with that option. I know that the first option's value is 1, for example, but can I write a script that will get the text - aaa?
     
    NoamBarz, Jun 7, 2007 IP
  2. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #2
    document.frm.bla.text;
     
    ajsa52, Jun 7, 2007 IP
  3. NoamBarz

    NoamBarz Active Member

    Messages:
    242
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    58
    #3
    Doesn't work...
     
    NoamBarz, Jun 7, 2007 IP
  4. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #4
    Try this, it's working for me on FireFox and explorer:
    
    <html>
    <head>
      <script type="text/javascript">
    	function f_selected(p_index)
    	{
    		var v = document.getElementsByTagName( "option" )[p_index];
    		alert( "value='" + v.value + "', text='" + v.text + "'" );
    	}
      
      </script>
    
    </head>
    <body>
    <select id="bla" onchange="f_selected(this.selectedIndex)">
      <option value='1'>aaa</option>
      <option value='2'>bbb</option>
      <option value='3'>ccc</option>
      </select>
    </body>
    </html>
    
    Code (markup):
     
    ajsa52, Jun 7, 2007 IP
    NoamBarz likes this.
  5. NoamBarz

    NoamBarz Active Member

    Messages:
    242
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    58
    #5
    It works. Thanks!
    What made the difference was the use of 'selectedIndex'.
    Rep added!
     
    NoamBarz, Jun 8, 2007 IP