KHansen
KHansen

Reputation: 930

Why does jQuery option:selected return first option when nothing is selected

When I use alert($("select").find("option:selected").val()); on a select that has no option selected, jQuery alerts the value of the first element within the select.

Why is that, and how do I get my expected return value of '' or even undefined?

Link to fiddle: jsfiddle

alert($(".select").find("option:selected").val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select">
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
  <option value="3">Test 3</option>
  <option value="4">Test 4</option>
  <option value="5">Test 5</option>
</select>

Upvotes: 1

Views: 56

Answers (2)

mplungjan
mplungjan

Reputation: 178401

That is a good question. After investigating the source code, it seems that jQuery will return the value under the selectedIndex and it is 0 in both the cases below

My recommendation is to have a "Please select" without value - you can disable it so it is not sent to the server.

That also means your select will trigger onchange when the first actual value is selected AND HTML5 validation will make a required work

console.log($(".select1 option:selected").val(),
            $(".select2 option:selected").val());
console.log($(".select1")[0].selectedIndex,
            $(".select2")[0].selectedIndex);  
$(".select1 option").each(sel => console.log(sel.defaultSelected) )
$(".select2 option").each(sel => console.log(sel.defaultSelected) )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select1">
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
  <option value="3">Test 3</option>
  <option value="4">Test 4</option>
  <option value="5">Test 5</option>
</select>

<select class="select2">
  <option value="">Please select</option>
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
  <option value="3">Test 3</option>
  <option value="4">Test 4</option>
  <option value="5">Test 5</option>
</select>

Upvotes: 2

Ahmed Ali
Ahmed Ali

Reputation: 1964

As your first option is selected as default then create an another option and set attributes of selected and disabled, Because user will not select that option

alert($(".select").find("option:selected").val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select">
  <option selected disabled value="">Select Any Item</option>
  <option value="1">one</option>
  <option value="2">two</option>
  <option value="3">three</option>
  <option value="4">four</option>
</select>

Upvotes: 0

Related Questions