Home > OS >  Multiple select goes up after selection
Multiple select goes up after selection

Time:11-24

I'm working on an HTML form opened in Google sheets with Google App Script.

I use two multiple dropdowns in a filter form. I used a code to avoid ctrl click when the user selects options. The filter works but there's a bug: when I scroll down and select an option, the option is selected but the dropdown goes up automatically.

Here's my code with bug (https://stackoverflow.com/a/27578356/15994269) :

  // Allows to select mutiple options in a multiple select form without ctrl   click
  window.onmousedown = function (e) {
      var el = e.target;
      if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
          e.preventDefault();

          // Toggle selection
          if (el.hasAttribute('selected')) el.removeAttribute('selected');
          else el.setAttribute('selected', '');

          // Hack to correct buggy behavior
          var select = el.parentNode.cloneNode(true);
          el.parentNode.parentNode.replaceChild(select, el.parentNode);
      }
  }

I've made some researches to resolve this issue and try to merge some solutions to my code and I think those one are getting close of what I'm looking for :

https://stackoverflow.com/a/27056015/15994269

https://stackoverflow.com/a/60660662/15994269

But I was not successful.

Thanks for your answers.

CodePudding user response:

I think there may be better way but you may try:

let selectTop;

window.onmousedown = function (e) {
    var el = e.target;
    if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
        e.preventDefault();

        // toggle selection
        if (el.hasAttribute('selected')) el.removeAttribute('selected');
        else el.setAttribute('selected', '');

        selectTop = el.parentNode.scrollTop;
    }
}

document.querySelector('select').addEventListener('scroll', (e) => {
  if (selectTop) { e.target.scrollTop = selectTop };
  selectTop = 0;
});
<h4>From</h4>

<div>
    <select name="sites-list" size="7" multiple>
        <option value="site-1">SITE</option>
        <option value="site-2" selected>SITE</option>
        <option value="site-3">SITE</option>
        <option value="site-4">SITE</option>
        <option value="site-5">SITE</option>
        <option value="site-6" selected>SITE</option>
        <option value="site-7">SITE</option>
        <option value="site-8">SITE</option>
        <option value="site-9">SITE</option>
    </select>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related