1

I have tried using both of these methods and none seem to retrieve the selected value or text of from the drop down menu.

My HTML:

<select id="sessions">
  <option value="0">Choose a Session</option>
  <option value="Awesome">Awesome</option>
  <option value="test1">test1</option>
  <option value="testing">testing</option>
</select>

First Method:

var selectedSession = $('#sessions').options[$('#sessions').selectedIndex].val();

This doesn't even get recognized since I get a an undefined value returned.

Second Method:

var selectedSession = $('#sessions').find(":selected").text();

This returns the string "". A blank. I have tried both val() and text(). And yes, I know the difference between the two.

EDIT:

Tried all of these methods with no success:

var selectedSession = $('#sessions :selected').text();
var selectedSession = $('#sessions').val();
var selectedSession = $('#sessions option:selected').text();
var selectedSession = $('select#sessions').val();
var selectedSession = $('#sessions')[0].options[$('#sessions')[0].selectedIndex].val();
var selectedSession = document.getElementById("sessions").text(); Returns null

Also, to clarify, the javascript is in an external document (eg. external.js) and The variable is global and not inside any function.

Thanks for the help.

10100111001
  • 1,832
  • 1
  • 11
  • 7

3 Answers3

1

try this:

to get text of option:

$( "#sessions option:selected" ).text();

to get value of option:

$('select#sessions').val()
Gupta
  • 73
  • 5
0

You can call val() directly on the select

var selectedSession = $('#sessions').val();

The problem with your first method is that you're mixing up jQuery and native DOM methods, there is no options or selectedIndex property on a jQuery object, you'll have to do that on the select element itself. e.g. $('#sessions')[0].options, $('#sessions')[0].selectedIndex

Musa
  • 96,336
  • 17
  • 118
  • 137
0

Try with $('select#sessions').val()

Here val is the value of the property
Here text is the value of the property.


Sample:
For val is '0', text is 'Choose a Session'
For val is 'Awesome' , text is Awesome.


Value represents option value
text represent the value between the tags. 


<select id="sessions">
  <option value="0">Choose a Session</option>
  <option value="Awesome">Awesome</option>
  <option value="test1">test1</option>
  <option value="testing">testing</option>
</select>
Sireesh Yarlagadda
  • 12,978
  • 3
  • 74
  • 76