Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
How do I scroll an HTML multiple-selection select box to the first selected option?

I am trying to get an HTML multiple-selection select box to scroll to the first selected option, but I cannot find any way of doing so. Is there a way?

<select id=s multiple> 
<option value=0>One</option>
...

<option value=99 selected>Many</option>
</select>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use the below function that will look for the first selected element in your list, and will scroll the select box to it.

Make sure you call the function when you already have the selections loaded, usually on window.onload event, but if you're populating the selections with ajax call, the function needs to be called respectively (once the selections are already in place)


// this is how you call the function, using the ID ("s") in your example:
window.onload = function(){
 scrollToSelected( "s" )
}

function scrollToSelected( select_id ) {
  var select = document.getElementById( select_id );
  var opts = select.getElementsByTagName('option');
  for ( var j = opts.length -1; j > 0; --j ) {
    if ( opts.item(j).selected == true ) {
      select.scrollTop = j * opts.item(j).offsetHeight;
      return;
    } 
  }
}

With the following line you can set the exact scroll position:

select.scrollTop = j * opts.item(j).offsetHeight;

... the above will attempt to scroll until the selected will be in the top of the list.

about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks for your advice.

It seems that I cannot post code in a comment, so I will need to put this here. What seems to work is height: 20px; in the CSS for the option tag and the following Javascript:

 var select = document.getElementById(select_id);
    if (!select) console.error("no " + select_id);
    var opts = select.getElementsByTagName('option');
    var j = select.selectedIndex;
    if (j == -1) return;
    select.scrollTop = j * 20;

I'm getting 0 for the option's offsetHeight but hard coding a value as above seems to work.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda