jQuery get selected option value (not the text, but the attribute 'value')

后端 未结 14 1995
长情又很酷
长情又很酷 2020-11-29 18:13

Okay, I have this code:


                        
    
提交评论

  • 2020-11-29 18:34

    Look at the example:

        <select class="element select small" id="account_name" name="account_name"> 
    
            <option value="" selected="selected">Please Select</option>           
            <option value="paypal" >Paypal</option>
            <option value="webmoney" >Webmoney</option>
    
        </select>
    
     <script type="text/javascript">
    
            $(document).ready(function(){ 
                 $('#account_name').change(function(){
                   alert($(this).val());                                                          
                 });
            });
     </script>
    
    0 讨论(0)
  • 2020-11-29 18:38

    One of my options didn't have a value: <option>-----</option>. I was trying to use if (!$(this).val()) { .. } but I was getting strange results. Turns out if you don't have a value attribute on your <option> element, it returns the text inside of it instead of an empty string. If you don't want val() to return anything for your option, make sure to add value="".

    0 讨论(0)
  • 2020-11-29 18:38

    this code work very well for me: this return the value of selected option. $('#select_id').find('option:selected').val();

    0 讨论(0)
  • 2020-11-29 18:38

    It's working better. Try it.

    let value = $("select#yourId option").filter(":selected").val();

    0 讨论(0)
  • 2020-11-29 18:39

    Source Link

    Use jQuery val() to GET Selected Value and and text() to GET Option Text.

        <select id="myDropDown" class="form-control">
            <option value="0">Select Value 0</option>
            <option value="8">Option value 8</option>
            <option value="5">Option value 5</option>
            <option value="4">Option value 4</option>
        </select>
    

    Change Event on Select Dropdown

            $("#myDropDown").change(function () {
    
                // Fetching Value
                console.log($(this).val());
    
                // Fetching Text
                console.log($(this).find('option:selected').text());
    
                alert('Value: '+$(this).val()+' | Text: '+$(this).find('option:selected').text());
            });
    

    Button Click

            $("button").click(function () {
    
            // Fetching Value
                console.log($("#myDropDown").val());
    
        // Fetching Text
                console.log($('#myDropDown option:selected').text());
    
                alert('Value: '+$("#myDropDown").val()+' | Text: '+$('#myDropDown option:selected').text());
            });
    
    0 讨论(0)
  • 提交回复
    热议问题