jQuery get specific option tag text

2018-12-31 16:49发布

All right, say I have this:

<select id='list'>
    <option value='1'>Option A</option>
    <option value='2'>Option B</option>
    <option value='3'>Option C</option>
</select>

What would the selector look like if I wanted to get "Option B" when I have the value '2'?

Please note that this is not asking how to get the selected text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:

$("#list[value='2']").text();

But it is not working.

20条回答
余欢
2楼-- · 2018-12-31 17:40

You can get one of following ways

$("#list").find('option').filter('[value=2]').text()

$("#list").find('option[value=2]').text()

$("#list").children('option[value=2]').text()

$("#list option[value='2']").text()

$(function(){    
    
    console.log($("#list").find('option').filter('[value=2]').text());
    console.log($("#list").find('option[value=2]').text());
    console.log($("#list").children('option[value=2]').text());
    console.log($("#list option[value='2']").text());
    
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id='list'>
    <option value='1'>Option A</option>
    <option value='2'>Option B</option>
    <option value='3'>Option C</option>
</select>

查看更多
与君花间醉酒
3楼-- · 2018-12-31 17:41

If you'd like to get the option with a value of 2, use

$("#list option[value='2']").text();

If you'd like to get whichever option is currently selected, use

$("#list option:selected").text();
查看更多
梦寄多情
4楼-- · 2018-12-31 17:42

Use:

function selected_state(){
    jQuery("#list option").each(function(){
        if(jQuery(this).val() == "2"){
            jQuery(this).attr("selected","selected");
            return false;
        }
    });
}

jQuery(document).ready(function(){
    selected_state();
});
查看更多
姐姐魅力值爆表
5楼-- · 2018-12-31 17:44

It's looking for an element with id list which has a property value equal to 2. What you want is the option child of the list.

$("#list option[value='2']").text()
查看更多
素衣白纱
6楼-- · 2018-12-31 17:44

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();
查看更多
看淡一切
7楼-- · 2018-12-31 17:45
$("#list option:selected").each(function() {
   alert($(this).text());
});  

for multiple selected value in the #list element.

查看更多
登录 后发表回答