Nate Pet
Nate Pet

Reputation: 46222

Jquery get the key/value - key from asp drop down

I have the following in my code:

    <asp:DropDownList id="City" runat="server">

I tried using the following to get the key from the key value but it shows up as undefined although I selected from the dropdown

    var city = $("#city option:selected").val();

    alert(city);

Upvotes: 0

Views: 1034

Answers (3)

James Johnson
James Johnson

Reputation: 46047

I'm not entirely sure what you mean by key and value, but I'm assuming you mean the text and value of the selected option. Try something like this:

var selectedOption = $("#<%= City.ClientID %> option:selected");
if (selectedOption){
    alert($(selectedOption).text() + "/" + $(selectedOption).val());
}

Upvotes: 0

valen
valen

Reputation: 845

The cases don't match between the ID and the selector.

var city=$("#City option:selected").val();

Upvotes: 0

maxedison
maxedison

Reputation: 17553

You should simply use the .val() method on the select element itself, rather than searching for the option:selected child (as you're currently doing). IDs in CSS are also case-sensitive.

var city = $("#City").val();
alert(city);

Upvotes: 1

Related Questions