Dropdown options can't access with jquery selector?

I have a drop down in my webpage.It's a aspx page.But i am try to access the drop down from JavaScript.here is my code. This code is working.

var a = document.getElementById('myDropdown');
alert(a.options.length);

This code is not working

var a = $('#myDropdown');
alert(a.options.length);

i am getting the following error.

TypeError: Cannot read property 'length' of undefined

Any one have any idea.

Upvotes: 0

Views: 69

Answers (3)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

Jquery and js doesnt select the same thing.

There is 2 way to get the number of action with JQ :

$('#dropdown')[0].options.lenght; //That select the container like getElement

or

$('#dropdown').children().length // That's pure jq counting the children (options)

Upvotes: 0

Craig Heneveld
Craig Heneveld

Reputation: 389

$('#myDropdown') is a jQuery object and you are treating a like a dom object. Try changing

var a = $('#myDropdown');

to

var a = $('#myDropdown')[0];

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

Use the clientID, ASPX controls are rendered differently on the page. You can also target the controls class using normal selectors.

var a = $('#<%=myDropdown.ClientID%>'); <-- ID
var b = $(".className") <--- Class selector.

Upvotes: 0

Related Questions