Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

This always returns null for some reason?

 alert($(element).val("option :first-child").val());
like image 439
john doe Avatar asked Sep 22 '14 23:09

john doe


1 Answers

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"
like image 117
Shai Avatar answered Sep 28 '22 04:09

Shai