Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery v1.10+ val() creates empty option if none exists

Tags:

jquery

Recently updated to jQuery v1.12 and found that it sets <select> elements to a nonexistant option if one doesn't exist, instead of gracefully falling back to unsetting the value as it did previously.

Here is the behavior I'm used to (pre v1.10):

$("button").click(function() {
  $("select").val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select>
  <option value="1">something 1</option>
  <option value="2" selected="selected">something 2</option>
</select>
<button>reset</button>

And here is how v1.10+ behaves:

$("button").click(function() {
  $("select").val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select>
  <option value="1">something 1</option>
  <option value="2" selected="selected">something 2</option>
</select>
<button>reset</button>

Is this a bug or is this the intended behavior?

I read through the changelog and don't see any specific mention of this change but finding it rather disruptive.

(Please note: I am not looking for workarounds and as noted in the comments, I've already changed my app to use $('select').prop("selectedIndex", 0).change();)

like image 313
Eaten by a Grue Avatar asked Jan 13 '17 17:01

Eaten by a Grue


1 Answers

jQuery automatically setting it to the first or default option was a bug which was fixed post jQuery 1.10+

See this link : https://bugs.jquery.com/ticket/13514

like image 187
philantrovert Avatar answered Sep 20 '22 08:09

philantrovert