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

199
Visualizações
Select2js: catch keydown events

For some reason, select2js seems to operate independently from the rest of my application as far as keydown events are concerned.

A simple example is preventing inputs:

$(() => {

  $("#select2-div").select2({
    maximumSelectionLength: 5,
    allowClear: true,
    tags: true,
    width: "75%",
    tokenSeparators: [',', ' '],
    dropdownParent: $("#select2-div").parent()
  })

  $(document).keydown((e) =>{
    e.preventDefault();
  })


});
<!doctype html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</head>

<body>

<div style="display: flex; justify-content: center; align-items:center; width: 400px;">
  <select multiple id="select2-div">
    <option value="yes">Yes</option>
    <option value="no">No</option>
    <option value="maybe">Maybe</option>
    <option value="idontknow">I don't know</option>
  </select>
  
  <input style="margin-left: 30px; width: 100px"type="text">
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</body>
</html>

Why is the user still able to input things in the select2 input (but, rightly so, not in the standard input)? How can I prevent this behaviour?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The event is dispatched in two phases, the default phase is the second one, "bubbling", which sends the event first to the innermost child where select2's listener is attached so it sees the event first, then the event bubbles up to document where your listener sees it.

The solution is to add a listener in the first event phase, "capturing", where the event descends (from window to document to body and down the DOM tree to the innermost element), by using the vanilla DOM addEventListener with the third parameter set to true. If you stop the event in a capturing listener, it won't be dispatched to the listeners in the next phase ("bubbling").

window.addEventListener('keydown', e => {
  e.preventDefault(); // disables the browser's default behavior
  e.stopPropagation(); // disables the bubbling phase listeners
}, true);

Disabling an individual key pressed inside a specific element:

window.addEventListener('keydown', e => {
  if (e.key === 'Escape' && e.target.closest('.select2-container')) {
    e.preventDefault(); // disables the browser's default behavior
    e.stopPropagation(); // disables the bubbling phase listeners
  }
}, true);

You can also use document here, which is the second target in the capturing phase.

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