Saleh Feek
Saleh Feek

Reputation: 2076

Hot to get the text of the selected option in jQuery?

td is a jQuery variable that references a table cell <td> element. This cell contains a <select> element which contains a number of <option> elements; each has a text and value.

This code returns the value (not text) of the selected option.

td.children().val();

I tried many ways to get the text of the selected option, but non of them work.

td.children().text() This returns the text of all the options of the <select> element.

I filtered it many ways but no result returned at all:
td.children(':selected').text()
td.children('option:selected').text()
td.children('[selected]').text()
td.children('[selected=""]').text()
td.children('option[selected=""]').text()

Upvotes: 0

Views: 219

Answers (1)

Satpal
Satpal

Reputation: 133403

Since option is immediate child of select not td the function children() will not work. Thus none of your attempted solution worked.

You need to use .find()

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

td.find('option:selected').text()

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

Upvotes: 1

Related Questions