Thursday, February 3, 2011

Getting the text from a drop-down box

This gets the value of whatever is selected in my dropdown menu.

document.getElementById('newSkill').value

I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at W3Schools but that didn't have the answer, does anybody here know?

For those not sure, here's the HTML for a drop down box.

<select name="newSkill" id="newSkill">
    <option value="1">A skill</option>
    <option value="2">Another skill</option>
    <option value="3">Yet another skill</option>
</select>

Thanks

  • Does this get the correct answer?

    document.getElementById("newSkill").innerHTML
    
  • document.getElementById('newSkill').options[document.getElementById('newSkill').selectedIndex].value 

    Should work

    From Thej
  • This should return the text value of the selected value

    var vSkill = document.getElementById('newSkill');
    
    var vSkillText = vSkill.options[vSkill.selectedIndex].innerHTML;
    
    alert(vSkillText);
    

    Props: @Tanerax for reading the question, knowing what was asked and answering it before others figured it out.

    Edit: DownModed, cause I actually read a question fully, and answered it, sad world it is.

    From Tanerax
  • Based on your example HTML code, here's one way to get the displayed text of the currently selected option:

    var skillsSelect = document.getElementById("newSkill");
    var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
    
    Teifion : For those late to the party, there were several suggestions but nobody noticed that they said .value where they should say .text, a confusing day for us all it was.

0 comments:

Post a Comment