views:

156

answers:

4

Hi all,

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.

+3  A: 
var selected = $("#id option:selected");
var value = selected.val();
Ben
A: 

I think this should work:

$("#id").attr("value")

...but it's been a while since I used jQuery.

David Thomas
There's no value attribute on the <select /> element, so this will give you nothing, basically.
Deeksy
Ah, yes. Umm...I *thought* it looked too obvious to be useful, I should've thought harder... =)
David Thomas
+1  A: 

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').

BalusC
AH! Thanks alot for that, awesome input.
Belkin
This is not quite true. val() does work on `option` elements according to <a href="http://docs.jquery.com/Attributes/val">official documentation.</a>
jkndrkn
Whoops, sorry for the broken link: http://docs.jquery.com/Attributes/val
jkndrkn
A: 

I'm assuming you will be triggering an event handler to capture this information, correct? If so, here is how I would access a selected value's "id" and "name" components:

    $('select').change(function () { 
        var id = $(":selected", this).val();
        var name = $(":selected", this).text();
    });

` There is a demo of this code in action here.

jkndrkn