How to get select box option value in jQuery

笑着哭i 提交于 2019-12-09 04:18:16

问题


How to get the value of option select box in jQuery if I have the code like this,

<select id='media' name='media'>
    <option value='1'>media1</option>
    <option value='2'>media2</option>
    <option value='3'>media3</option>
</select>

When I code for on change event,

$(document).ready(function()
{
    $("#media").change(function()
    {
        var id=$(this).val();
        var dataString = 'id='+ id;
        alert(id); return false;
    });
});

It gives me media1,media2,media3 instead of 1, 2, 3

How to get the value 1, 2, 3?


回答1:


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

Here id is the id of a select box. I'm sure it will work 100%.

If you want selected text use this one:

$("#id option:selected").text();



回答2:


$('#media').change(function(){
alert($(this).val());
});

this should work the way you want it should.




回答3:


try this,

jQuery(document).ready(function() {

    jQuery('#media').change(function(e) {

        var id = $(this,':selected').val();
        alert(id);

    });

});



回答4:


make sure you use latest jquery because its working fine

http://jsfiddle.net/Hayhv/

check it give value of option




回答5:


I did so,

<select id='coprede' name='cop_rede'>
<option value='1'>Cop Rio de Janeiro</option>
    <option value='2'>Cop Nordeste</option>
    <option value='3'>Cop Vitoria</option>
    <option value='4'>Cluster Norte</option>
    <option value='5'>Cluster Centro Oeste</option>
</select>

within the script:

$(function(){

$('#coprede').change(function(){
    alert($('#coprede :selected').val());
    });
});



回答6:


use this code:

$('#media').change(function(){
    alert($('#media :selected').val());// or $('#media').val();        
});​



回答7:


Use class instead of id like this..

<select class='media' name='media'>
    <option value='1'>media1</option>
    <option value='2'>media2</option>
    <option value='3'>media3</option>
</select>

$(document).ready(function(){
    $(".media").live("change",function(){
        var id = $(this).val();
        var dataString = 'id='+ id;
        alert(id); return false;
    }); 
}); 



回答8:


I have tested your code and its works ok for me make sure about id #media does repeat from other control. Because its config and get value from last find html control



来源:https://stackoverflow.com/questions/12489527/how-to-get-select-box-option-value-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!