selectedIndex is undefined with jQuery in dropdownlist

MarioDS picture MarioDS · May 6, 2012 · Viewed 8.2k times · Source

I have an ASP.NET dropdownlist like this:

<asp:DropDownList ID="ddlMyDropDown" runat="server">
        <asp:ListItem>Please pick one</asp:ListItem>
    <asp:ListItem>option1</asp:ListItem>
    <asp:ListItem>option2</asp:ListItem>
    <asp:ListItem>option3</asp:ListItem>
    <asp:ListItem>option4</asp:ListItem>
    </asp:DropDownList>

A CustomValidator is bound to it, to see if the user chose an option. It calls the following javascript/JQuery function:

function checkValueSelected(sender, args) {
        var index = $("#ContentPlaceHolder1_ddlMyDropDown").selectedIndex;
        args.IsValid = index > 0;
    }

but index is undefined when debugging with Firebug. The JQuery selector finds select#ContentPlaceHolder1_ddlMyDropDown, so that's not the problem. Does the selectedIndex property not exist?

On the internet I found examples that do almost exactly the same and it works. I'm quite lost on this one...

Update

This is what Firebug shows:

inspect

As you can see, the control variable is some sort of array, with one entry which is actually what I want to be in control. I don't think JQuery's ID selector returns multiple values?

Answer

Royi Namir picture Royi Namir · May 6, 2012

selectedIndex is not there ...

you should use prop of jquery...

var index = $("#ContentPlaceHolder1_ddlMyDropDown").prop('selectedIndex');

or

 var index = $("#ContentPlaceHolder1_ddlMyDropDown").get(0).selectedIndex;