john doe
john doe

Reputation: 9660

Get the value of the first option in a select list using jQuery

This always returns null for some reason?

 alert($(element).val("option :first-child").val());

Upvotes: 9

Views: 23453

Answers (2)

Shai
Shai

Reputation: 7317

It will vary slightly depending on what the element variable actually is, but:

If element is a native DOM element:

alert($(element).find("option:first-child").val());

Or if element is a jQuery-wrapped element already you can simplify to:

alert(element.find("option:first-child").val());

There were two bugs in what you were trying:

  • You were using val in place of find to find the option within the select
  • You had a space between option and :first-child, which means "find a first-child which is a descendant of an option element"

Upvotes: 15

Greg
Greg

Reputation: 10342

Looks like you're setting the val (to "option :first-child") then trying to read it. Maybe you meant to do this?

alert($(element).find("option:first-child").val());

Upvotes: 3

Related Questions