user1869407 user1869407 - 3 months ago 8
jQuery Question

How to retrieve the selected option of a select nested in a <td>

I have a loop that runs through all the table data. It works great for pulling "text here" string from html markup like "

<td>text here</td>
", but I have nested elements in some cells like "
<td><select><option>1</option><option>2</option><option>3</option></select><label>some other string</label></td>
"

This is the code I am trying to use to grab the selected option from the select element.

$(this).children().eq(0).find("option:selected");


The select element is the first element nested inside the
<td></td>
that is why it is
children().eq(0)


$(this)
is a
<td>...</td>


I was hoping
.find("option:selected");
would retrieve the selected option but it is not valid code.

Here is a structural example of what a common
<td>
tag contains:

<td><select><option>1</option><option>2</option><option>3</option></select><label>some other string</label></td>


I want the selected option for the first select tag in a td.

Answer

You can use val() method to get the selected option's value.

var val = $(this).find("select").eq(0).val();

With the assumption that $(this) is the td element in your context, in which you have the select element.

Comments