tags:

views:

97

answers:

4

I've got an asp.net control inside a masterpage, so I thought the following selector would get me the selected option for my drop down list, but it's in correct.

$("#input[id$='ddlTags'] option:selected")

Can anyone shed some light?

Thanks.

+6  A: 

Your problem is that your string looks for an item with id of both "input" and "ddlTags"

try changing it to

$("input#ddlTags option:selected")

or even just

$("#ddlTags option:selected")

for more details on selecting by id, see http://docs.jquery.com/Selectors/id

edit:

since you need it to survive mangling, try

$("input[id$=ddlTags] option:selected")

which is the same as your original, except that it now looks for "input" tags instead of tags with id "input"

cobbal
A: 

# stands for ID, so right now you're asking for elements with ID="input[id$='ddlTags'].

Gab Royer
+1  A: 

$(#[id$='ddlTags'] option:selected)

Seems to have worked.

RubbleFord
yes, but is still not the best way
cobbal
What if you try $("#ddlTags").val() ?
Draco
That won't work because ASP.NET mangles IDs when rendering.
mgroves
+1  A: 

Sometimes with master pages, or elements in a repeater, the actual client ID of controls gets mangled something fierce. However, you can send out the client ID to the client in your JavaScript. I'm going to assume your control is named ddlTags. :)

$('#<%= ddlTags.ClientID %> option:selected')

That'll give you back a jQuery object containing all the selected option tags. However, since you're using a ddl, I'm assuming it's a single select. If all you want is the value of the selection, you can get a bit simpler.

$('#<%= ddlTags.ClientID %>').val()

That gives you the value of the selected items within that element.

The <%= is shorthand for "echo this piece out to the client when rendering". It's a really handy piece in conjunction with jQuery.

Really, you want to use an ID-based selector like this over using something like input[id=<%= ddlTags.ClientID %>] because then jQuery can use browser-native functions to make the selection and it'll run a good bit faster.

Brian Arnold