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.
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.
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.
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').
Change your html to the valid value=
instead of val=
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')
try this :
$('#dropdownList option:selected').attr('val')
note : didnt tested
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With