chris
chris

Reputation: 36947

jquery find selects selected option within div

Trying to figure out how to get a selects selected option where there is no id or class to use as a selector, but is contained within a specific div (theres multiple selects on the page I only want this one).

Not sure if I should do something with find, parent, sibling, other... Example of what I am working with.

<div id="mydiv">

<select name="myselect">
<option selected="selected" value="1">Hi</option>
</select>

</div>

Upvotes: 3

Views: 33347

Answers (4)

Jasper
Jasper

Reputation: 76003

You can select by name:

var val = $('select[name="myselect"]').val();

Here is a list of ways to select using jQuery (it's awesomely long): http://api.jquery.com/category/selectors/

Since it's a child element you can also do this:

var val = $('#mydiv').children('select[name="myselect"]').val();

This starts with your DIV that has an ID, then gets the children of that element that are select element(s) with the name attribute set to myselect.

If your select element was not a direct descendant then you could use .find() instead:

var val = $('#mydiv').find('select[name="myselect"]').val()

Docs for ya:

Note that calling .val() in a select element will return the value of the selected option.

Upvotes: 2

Priyeshj
Priyeshj

Reputation: 1345

Try doing $('div#mydiv > select > option[selected="selected"]')

Upvotes: 0

Madbreaks
Madbreaks

Reputation: 19549

You can select it by name:

var sel = $('select[name=myselect]');

Cheers

Upvotes: 0

Alp
Alp

Reputation: 29739

You can use the > symbol to select direct children. :selected returns selected options.

jQuery('#mydiv > select[name=myselect] > option:selected')

If you want all selected options use this:

jQuery('option:selected')

To get the select elements of those selected options:

jQuery('option:selected').parent();

Upvotes: 2

Related Questions