Getting an option text/value with JavaScript

JavascriptHtmlFormsHtml Select

Javascript Problem Overview


Answer: var option_user_selection = element.options[element.selectedIndex].text

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.

Javascript Solutions


Solution 1 - Javascript

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text

Solution 2 - Javascript

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

Solution 3 - Javascript

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

Solution 4 - Javascript

form.MySelect.options[form.MySelect.selectedIndex].value

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilView Question on Stackoverflow
Solution 1 - JavascriptChanduView Answer on Stackoverflow
Solution 2 - JavascriptMorgansterView Answer on Stackoverflow
Solution 3 - Javascriptuser4386053View Answer on Stackoverflow
Solution 4 - JavascriptM99View Answer on Stackoverflow