简体   繁体   中英

Get selected option's text in an HTML select using jQuery

I have a html below. How can I get the text of second tag ie "Frame Size" .

<div class="productOptionViewSelect">
    <div class="selector fixedWidth" id="uniform-08876c63593c0928fefc45101870c7b0"><span style="-webkit-user-select: none;">Frame Size</span><select class="validation" id="08876c63593c0928fefc45101870c7b0" name="attribute[1318]">
        <option value="">-- Please Select --</option>

                    <option value="2527">Frame Size</option>
                    <option value="206">10x15 (4x6 in)</option>
            </select></div>
</div>


<div class="productOptionViewSelect">
        <div class="selector fixedWidth" id="uniform-08876c63593c0928fefc45101870c7b0"><span style="-webkit-user-select: none;">Frame Size</span><select class="validation" id="08876c63593c0928fefc45101870c7b0" name="attribute[1318]">
            <option value="">-- Please Select --</option>

                        <option value="252">Photo Size</option>
                        <option value="206">10x20 (4x6 in)</option>
                </select></div>
    </div>

I can get the value of the select by

$('.productOptionViewSelect').find('select').val();

But this will not fulfill my requirement. Any option can be selected so i can't use above jQuery.

Edit

If i have same block twice with different sets of option than how can i get the second option of each block? In this case i want Frame Size and Photo Size but in every event call it only returns Frame Size . Any help would be appreciated.

Use this

$('.productOptionViewSelect').find('select option:selected').text()

It will give you the text inside of the <option>

You cannot use selector like this:

$('.productOptionViewSelect option:eq(1)')

because in this result set only one of those options will have index 1 - the index of the second option in second .productOptionViewSelect div will get the index equal to the index of the last option in first div plus 2 .

Therefore yo should iterate over those 2 sets of options and use .text() :

$('.productOptionViewSelect').each(function(){
    console.log($(this).find('option:eq(1)').text());
});

Output:

Frame Size
Photo Size

如果要获取所选选项的文本,则需要获取所选选项的jquery对象,然后使用.text().html()获取其中的内部内容:

$('.productOptionViewSelect option:selected').text();

尝试

$('.productOptionViewSelect select').find('option:selected').text();
$("select.validation option:eq(1)").text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM