selectedIndex is undefined with jQuery in dropdownlist
Asked Answered
E

1

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?

Embezzle answered 6/5, 2012 at 12:49 Comment(2)
Can you use asp.net property to check this?Humor
@Humor I found out what's wrong, going to edit question.Embezzle
H
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;
Henbane answered 6/5, 2012 at 13:9 Comment(4)
Thanks, I just read that $("#id") is NOT the same as document.getElementById("id").Embezzle
See the comments here. 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.Embezzle
@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)Henbane
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)...Embezzle

© 2022 - 2024 — McMap. All rights reserved.