开发者

Question regarding select and option value="" using JQuery

开发者 https://www.devze.com 2022-12-10 09:10 出处:网络
let\'s say i have list looking like this: <select name=\"name\" id=\"id\"> <option value=\"10176232332\">David</option>

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 ex开发者_高级运维ample:

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


var selected = $("#id option:selected");
var value = selected.val();


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


I think this should work:

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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号