Get selected value of a dropdown's item using jQuery

后端 未结 30 1532
广开言路
广开言路 2020-11-22 06:48

How can I get the selected value of a dropdown box using jQuery?
I tried using

var value = $(\'#dropDownId\').val();

and



        
30条回答
  •  抹茶落季
    2020-11-22 07:07

    I know this is a terribly old post and I should probably be flogged for this pitiful resurrection, but I thought I would share a couple of VERY helpful little JS snippets that I use throughout every application in my arsenal...

    If typing out:

    $("#selector option:selected").val() // or
    $("#selector option:selected").text()
    

    is getting old, try adding these little crumpets to your global *.js file:

    function soval(a) {
        return $('option:selected', a).val();
    }
    function sotext(a) {
        return $('option:selected', a).text();
    }
    

    and just write soval("#selector"); or sotext("#selector"); instead! Get even fancier by combining the two and returning an object containing both the value and the text!

    function so(a) {
        my.value = $('option:selected', a).val();
        my.text  = $('option:selected', a).text();
        return my;
    }
    

    It saves me a ton of precious time, especially on form-heavy applications!

提交回复
热议问题