jQuery get specific option tag text

后端 未结 22 1653
-上瘾入骨i
-上瘾入骨i 2020-11-22 12:32

All right, say I have this:


                        
    
提交评论

  • 2020-11-22 13:07

    I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find... earlier):

    <script type="text/javascript">
        $(document).ready(function(){
            $("select[showChoices]").each(function(){
                $(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'>&nbsp;</span>");
                doShowSelected($(this).attr('id'));//shows initial selections
            }).change(function(){
                doShowSelected($(this).attr('id'));//as user makes new selections
            });
        });
        function doShowSelected(inId){
            var aryVals=$("#"+inId).val();
            var selText="";
            for(var i=0; i<aryVals.length; i++){
                var o="#"+inId+" option[value='"+aryVals[i]+"']";
                selText+=$(o).text()+"<br>";
            }
            $("#spn"+inId).html(selText);
        }
    </script>
    <select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
        <option selected="selected" value=1>opt 1</option>
        <option selected="selected" value=2>opt 2</option>
        <option value=3>opt 3</option>
        <option value=4>opt 4</option>
    </select>
    
    0 讨论(0)
  • 2020-11-22 13:08

    This is an old Question which has not been updated in some time the correct way to do this now would be to use

    $("#action").on('change',function() {
        alert($(this).find("option:selected").text()+' clicked!');
    });
    

    I hope this helps :-)

    0 讨论(0)
  • 2020-11-22 13:08

    As an alternative solution, you can also use a context part of jQuery selector to find <option> element(s) with value="2" inside the dropdown list:

    $("option[value='2']", "#list").text();
    
    0 讨论(0)
  • 2020-11-22 13:08

    Try

    [...list.options].find(o=> o.value=='2').text
    

    let text = [...list.options].find(o=> o.value=='2').text;
    
    console.log(text);
    <select id='list'>
        <option value='1'>Option A</option>
        <option value='2'>Option B</option>
        <option value='3'>Option C</option>
    </select>

    0 讨论(0)
  • 2020-11-22 13:09

    I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:

    element.options[element.selectedIndex].text
    

    This of course uses the DOM object instead of parsing its HTML with nodeValue, childNodes, etc.

    0 讨论(0)
  • 提交回复
    热议问题