Search code examples
jquerydrop-down-menuhtml-select

jQuery: Get option innerHTML of first option with value set in HTML select tag


Suppose I have a dropdown (select tag) with 3 values. Our first option has a value of "". The second option has a value of "something". And the 3rd option has a value of "something else". How can I get the innerHTML (text) of the 2nd option? I don't want to hard code it such that it takes the 2nd option every time though. I want to make sure it's the first option with a value set.


Solution

  • var result = $('#selectId option[value!=""]').first().html();
    

    or:

    var result = $('#selectId option[value!=""]:first').html();
    

    Attribute Not Equal selector:

    Description: Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

    :first selector

    Description: Selects the first matched element. The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1)

    Note that all of the <option>s must have the value attribute in order for the selector to work as expected. If it's not guaranteed use this:

    var result = $('#selectId option[value!=""][value]:first').html();
    

    Has Attribute Selector [name]

    Description: Selects elements that have the specified attribute, with any value.