Trying to get the text value of a selected option from a select

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chanshaw
    New Member
    • Nov 2008
    • 67

    Trying to get the text value of a selected option from a select

    Hi I'm trying to get the text from the selected <option> of a <select>

    Code:
    function loadSelectQuestion()
    {
    	var dropdownIndex = document.getElementById('selectCategory').value;
    	document.getElementById('selectQuestion').innerHTML = dropdownIndex;
    }
    I can get the value of the select but if I try doing .text instead of .value i get an undefined responce.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    Originally posted by chanshaw
    I can get the value of the select but if I try doing .text instead of .value i get an undefined responce.
    because there is no such property in the HTML element (resp. in its JavaScript representation)

    Comment

    • chanshaw
      New Member
      • Nov 2008
      • 67

      #3
      I'm sorry, I don't understand. So I can't get the text value of the selected option with javascript?

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        you can get the text value, but you have to do it properly.

        assuming you already have the option element, there are several ways
        Code:
        // the option element is referenced through "opt"
        
        // for browsers which support textContent
        text = opt.textContent;
        
        // DOM level 1 (works everywhere, but not very elegant)
        // if there is only text inside the option element 
        text = opt.firstChild.nodeValue;

        Comment

        • acoder
          Recognized Expert MVP
          • Nov 2006
          • 16032

          #5
          The .text is a property of the <option> element/object, not the <select> element, so get the selected option to get the text:
          Code:
          sel.options[sel.selectedIndex].text
          where 'sel' is a reference to the select object.

          Comment

          • chanshaw
            New Member
            • Nov 2008
            • 67

            #6
            perfect thank you much

            Code:
            var theCategory = selectCategory.options[selectCategory.selectedIndex].text

            Comment

            • acoder
              Recognized Expert MVP
              • Nov 2006
              • 16032

              #7
              No problemo .

              Comment

              Working...