javascriptjqueryselectselectedtext

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 i.e. "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.


Solution

  • 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