11

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?

MarioDS
  • 12,895
  • 15
  • 65
  • 121

1 Answers1

8

selectedIndex is not there ...

you should use prop of jquery...

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

or

 var index = $("#ContentPlaceHolder1_ddlMyDropDown").get(0).selectedIndex;
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • Thanks, I just read that `$("#id")` is NOT the same as `document.getElementById("id").` – MarioDS May 06 '12 at 13:11
  • See the comments [here](http://api.jquery.com/id-selector/). Apparantly it is not the same, see my Firebug screenshot. The id selector returns an array, it will return a DOM element if done by `document.getElementById`. – MarioDS May 06 '12 at 13:14
  • 1
    @MarioDeSchaepmeester jQuery ALWAYS work with arrays . even if you think you have 1 id , some other guy can set multiple same id's (bad practice) - but still jquery will be able to work with them. ( the first one IMHO) – Royi Namir May 06 '12 at 13:15
  • And that's what I didn't know. I'm new to it, see. Strange that the ID selector does so too, since everyone would always append `.get(0)`... – MarioDS May 06 '12 at 13:16