Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with .append(), select lists, and Chrome 81

As of Chrome 81 release, pulling options from a select list and re-adding them with .append() does not seem to work as expected. This behavior was working in Chrome 80, and continues to work in other browsers. Am I doing something wrong, or is this a bug in Chrome?

Example code steps

  • get the select list
  • get the options from it (in production code I'm manipulating them, but for this example am not)
  • remove the options from the list
  • re-add the options to the list

Expected behavior

list has options

Actual behavior

no options shown, though DOM inspector shows that they are present

Snippet

function test() {
   var selectItem = $("#selectOne");
   var items = selectItem.find('option');
   selectItem.empty();
   selectItem.append(items);  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectOne" multiple>
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
  <option>E</option>
</select>

<br/>

<button onclick="test()">Go</button>

Adding the following line to the end of my javascript does "fix" the problem:

selectItem.get(0).innerHTML = selectItem.get(0).innerHTML;

However this is clearly not an actual fix. I only include it here in case it helps someone who understands this more than I do to pinpoint the problem.

EDIT 21 April: https://bugs.chromium.org/p/chromium/issues/detail?id=1073172 (thanks to whomever opened this!)

like image 343
Daniel Avatar asked Apr 14 '20 23:04

Daniel


1 Answers

Clone your option's , by doing that it will render the options again,

this it's the only line that you need to change

var items = selectItem.find('option');

to this

var items = selectItem.find('option').clone();

function test() {
   var selectItem = $("#selectOne");
   var items = selectItem.find('option').clone();
   selectItem.empty();
   selectItem.append(items);  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectOne" multiple>
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
  <option>E</option>
</select>

<br/>

<button onclick="test()">Go</button>
like image 150
Juan Avatar answered Nov 19 '22 11:11

Juan