Disappearing Elements When Moving Options Between Select Lists
Solution 1:
This appears to be a browser rendering bug. I'm unable to figure out exactly why it happens, but it appears that the use of sort logic after the quick detach/remove/append operations causes the browser renderer to get confused. If you look at the DOM inspector you can see the option
element are in the correct place, however the renderer does not display them.
I'd suggest raising this as a bug with the browser vendors.
The only workaround I've found for this is to trigger a focus
event on the target select
to force the element to be re-drawn in the DOM. The blur
is not necessary for this fix, it's only to avoid the CSS outline appearing around the selected element which is a little jarring.
Also note that I genericised the logic using data
attributes on both select
elements and buttons.
let els = {
from: $('#from'),
to: $('#to')
};
$('.move').click(function() {
let $target = els[this.dataset.target];
let $source = els[this.dataset.source];
$source.children('option:selected').appendTo($target);
$target.children('option').sort(sortAlpha).appendTo($target);
$target.focus().blur();
});
letsortAlpha = (a, b) => parseInt(a.textContent, 10) > parseInt(b.textContent, 10) ? 1 : -1;
body {
background-color: #a3d5d3;
}
select {
width: 200px;
height: 200px;
}
button {
width: 100px;
padding: 5px;
margin: 05px5px5px;
}
#button-container {
display: inline-block;
vertical-align: top;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><selectid="from"multiple><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option></select><divid="button-container"><buttonclass="move"id="moveRight"data-target="to"data-source="from">-></button><br /><buttonclass="move"id="moveLeft"data-target="from"data-source="to"><-</button></div><selectid="to"multiple></select>
Post a Comment for "Disappearing Elements When Moving Options Between Select Lists"