62

I am trying to build a form that fills in a person's order.

<form name="food_select">
    <select name="maincourse" onchange="firstStep(this)">
        <option>- select -</option>
        <option text="breakfast">breakfast</option>
        <option text="lunch">lunch</option>
        <option text="dinner">dinner</option>
    </select>
</form>

What I'm trying to do is send in the select object, pull the name and the text/value from the option menu AND the data in the option tag.

function firstStep(element) {
    //Grab information from input element object
    /and place them in local variables
    var select_name = element.name;
    var option_value = element.value;
}

I can get the name and the option value, but I can't seem to get the text="" or the value="" from the select object. I only need the text/value from the option menu the user selected. I know I can place them in an array, but that doesn't help

var option_user_selection = element.options[ whatever they select ].text 

I also need to use the passed in select reference as that is how it's set up in the rest of my code.

Later on, that text/value is going to be used to pull the XML document that will populate the next select form dynamically.

Phil
  • 10,948
  • 17
  • 69
  • 101
  • 3
    http://stackoverflow.com/questions/1085801/how-to-get-the-selected-value-of-dropdownlist-using-javascript – trante Feb 04 '14 at 18:58
  • 1
    Using jQuery you could do something like `jQuery('#mySelect option[value=myValue]')` – Michel Ayres Jul 15 '15 at 18:58
  • 3
    Possible duplicate of [Retrieving the text of the selected – Monir Tarabishi Sep 30 '16 at 06:24
  • Possible duplicate of [Get selected value in dropdown list using JavaScript?](http://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – totymedli Jan 11 '17 at 23:12
  • 1
    rofl, this was 5 years ago... – Phil Jan 12 '17 at 17:10

4 Answers4

76

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text
Phil
  • 10,948
  • 17
  • 69
  • 101
Chandu
  • 81,493
  • 19
  • 133
  • 134
7

In jquery you could try this $("#select_id>option:selected").text()

Andy
  • 49,085
  • 60
  • 166
  • 233
Morganster
  • 311
  • 2
  • 7
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/10574392) – sergdenisov Dec 15 '15 at 22:17
  • why not? he want the text of the selected value.... that code returns the selected text on the select... – Morganster Dec 16 '15 at 22:55
  • 1
    It seems like he is not using jq maybe thats why. – ymutlu Jun 01 '16 at 22:38
4
var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text
3
form.MySelect.options[form.MySelect.selectedIndex].value
Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
M99
  • 1,859
  • 10
  • 28
  • 50