Changing content of a dropdown list while it's

2019-02-26 02:02发布

问题:

I have a dropdown list populated with some items. When the user selects one of them, I would like the dropdown list to stay open and be repopulated with new items. The user then selects one of these and finally the dropdown closes.

Can it be done in JavaScript? And if so, how?

回答1:

Not without replacing the native control with a custom one.



回答2:

For science! I've created an alternative answer to test this. You can check this fiddle that contains this HTML:

<select id="y">
    <option>click to open dropdown</option>
    <option>do not choose this!</option>
</select>

And the following Javascript:

var t = 10;

var x = window.setInterval(function() {
    console.log(--t);
    if (t === 0) { act(); }
}, 1000);

function act() {
    var select = document.getElementById('y');
    var newOption = document.createElement('option');
    newOption.innerHTML = "this option will not appear if the select is open while it's added";
    select.appendChild(newOption);
}

If you open the dropdown and keep it opened until the timer expires, you will see the following behavior:

  • ✗ Chrome 29: option not visible until reopen + dropdown accomodates for width of new option;
  • ✗ IE10/9/8: same as Chrome 29 + it forcibly collapses the opened dropdown
  • ✓ Firefox 23: adds option without need for reopen + adjusts width for new option