Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an option text/value with JavaScript

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.

like image 352
Phil Avatar asked Jan 09 '11 21:01

Phil


People also ask

How do I find the value of an option tag?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).

How do you get selected option text in react JS?

The text of an option is simply the label property of the corresponding item . In your case, to retrieve the text of the selected option, you can do: var selectedItem = this.

What is option value in JavaScript?

Definition and UsageThe value property sets or returns the value of the option (the value to be sent to the server when the form is submitted). Tip: If the value property is not specified for an option element, then the text content will be sent to the server when the container form is submitted.


2 Answers

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text 
like image 127
Chandu Avatar answered Sep 24 '22 20:09

Chandu


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

like image 37
Morganster Avatar answered Sep 23 '22 20:09

Morganster