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

12,990

Solution 1

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.

Solution 2

If i am getting right you want to get 2nd elment from dropdown try

   $('select[name=thename] option:eq(1)').text();​
Share:
12,990
MacGyver
Author by

MacGyver

My friends call me "Mac". I'm a master of improvisation. I have vast scientific knowledge and unique abilities to use ordinary objects to get myself and friends out of trouble. I typically carry my Swiss Army knife and a roll of duct tape with me at all times. I dislike guns because of a traumatic childhood incident. I try to avoid violence whenever possible. Because my life was getting too stressful at the Phoenix Foundation, I have picked up programming as a new career. I spend my spare time on Stack Overflow.

Updated on November 21, 2022

Comments

  • MacGyver
    MacGyver over 1 year

    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.

  • gdoron is supporting Monica
    gdoron is supporting Monica about 12 years
    Where is the value not empty part? Read the question again please: "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."
  • MacGyver
    MacGyver about 12 years
    +1 Suppose I wanted to select that rather than just getting the innerhtml. Would I just set the attr function of "selected" to "selected"?
  • gdoron is supporting Monica
    gdoron is supporting Monica about 12 years
    @MacGyver Yes: $('#selectId option[value!=""]').first().attr('selected', 'selected')
  • Dusty
    Dusty about 10 years
    If you've got value setting for all options, this will always return the first option, but you can change it to say something like $('#selectId option[selected!=""]').first().html();