jQuery: Get option innerHTML of first option with value set in HTML select tag
Solution 1
var result = $('#selectId option[value!=""]').first().html();
or:
var result = $('#selectId option[value!=""]:first').html();
Description: Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.
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();
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();
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, 2022Comments
-
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 about 12 yearsWhere 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 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 about 12 years@MacGyver Yes:
$('#selectId option[value!=""]').first().attr('selected', 'selected')
-
Dusty about 10 yearsIf 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();