Search code examples
jqueryselectedindex

Question regarding select and option value="" using JQuery


let's say i have list looking like this:

<select name="name" id="id">
    <option value="10176232332">David</option>
    <option value="10187232332">Sven</option>
    <option value="10202232332">Ololf</option>
    <option value="10219232323">Jan</option>
    <option value="10230232323">Gustaf</option>
</select>

Using JQuery, how can i extract the value for each option - for example:

<option value="10176232332">David</option>

Where 10176232332 is the value. Using:

($("#id").val()) 

extracts the names, not the number combinations. Using regluar Javascript i would use:

list.options[list.selectedIndex].value;

Is there a "JQuery way" of doing that or should i stick to the above?

Thanks in advance for any help.


Solution

  • The val() function only works for input elements (input, select, textarea, button). The option element is not an input element.

    As said before, you need to handle it as a "normal" element, get it by option.attr('value').