Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the selected option value (NOT text) from dropdown with jQuery

Tags:

jquery

I have a dropdown like so:

<select id="dropdownList">
  <option val="1">Item One</option>
  <option val="2">Item Two</option>
  <option val="3">Item Three</option>
</select>

When I use $('#dropdownList').val(), the value returned is "Item One/Two/Three" rather than the actual option value (1/2/3), which is what I need. I'm not sure if I should be using something other than .val()? I apologize if this has been answered somewhere, but my Google-fu is failing me on this one.

like image 390
persephone Avatar asked Feb 05 '11 01:02

persephone


People also ask

How do I get the text value of a selected option jQuery?

We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.

How do I get the selected value of dropdown?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How do you check if a dropdown is selected in jQuery?

A more direct jQuery method to the option selected would be: var selected_option = $('#mySelectBox option:selected'); Answering the question .is(':selected') is what you are looking for: $('#mySelectBox option').


3 Answers

Change your html to the valid value= instead of val=

like image 180
The Scrum Meister Avatar answered Oct 23 '22 05:10

The Scrum Meister


Try this instead:

<select id="dropdownList">
  <option value="1">Item One</option>
  <option value="2">Item Two</option>
  <option value="3">Item Three</option> <!-- this works -->
  <option val="3">Item Three</option>   <!-- this is what you HAD before -->
</select>

Or if that's not an option, then get the selected index and look for the $(this).attr('val')

like image 24
jcolebrand Avatar answered Oct 23 '22 03:10

jcolebrand


try this :

$('#dropdownList option:selected').attr('val')

note : didnt tested

like image 45
Shlomi Komemi Avatar answered Oct 23 '22 03:10

Shlomi Komemi