bba
bba

Reputation: 15231

jquery selector help

I have a div with an id="my_div". How can I find a <select> by name (i.e. name="my_select") assuming that the <select> can be at any level underneath the div? I.e. it can be a child, grandchild etc. Ultimately I need to get the value of the selected option.

Upvotes: 2

Views: 45

Answers (2)

John Hartsock
John Hartsock

Reputation: 86892

This should work

var mySelect = $('#my_div select[name="my_select"]')[0]

This will get you the selected option. Meaning the actual DOM Element

alert(mySelect.options[mySelect.selectedIndex].value);
alert(mySelect.options[mySelect.selectedIndex].text)

Upvotes: 1

user113716
user113716

Reputation: 322592

This will search through all descendants of #my_div for <select> elements where the name attribute equals my_select.

var $select = $('#my_div select[name="my_select"]')

To get the value of the currently selected option, use .val().

var value = $select.val();

Upvotes: 3

Related Questions