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

194
Visualizações
How to know if a select2 has options

I don't need to know if you have options selected, I just need to know if you have options available. In case I have one or more options, I want to manually add another option that is “all”. And by default it is selected.

I have seen that the following is used on the internet, but I have tried it and it always gives me 1. It does not matter if there are 2 options, 1 or none.

$('#myselect option').length == 0

$('#myselect').has('option').length == 0

var menu = getElementById("select_id");
if(menu.options.length) {
    // has children
} else {
    // empty
}

$("#myselect option").length > 0

Naturally I have changed the identifier for mine.

Would someone know how to do it?

Thanks in advance

My code is this:

$("#terminal_bookings").select2({
            ajax: {
                url: '{{ route('get_search_terminals_booking', ['client' => $client]) }}' + data,
                dataType: 'json',
                data: function (params) {
                    return {
                        q: params.term,
                    };
                },
                processResults: function (response) {
                    return {
                        results: response
                    };
                },
                cache: true
            },
            language: {
                inputTooShort: function () {
                    return '{{ trans('common.insert_chars') }}';
                }
            }
        });

But when I put

console.log($("#terminal_bookings > option").length); 

return 1 ever, when I have 0 o 1 o 2 options.

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

0

Use $("#myselect > option").length to check if there are any options(children),

if ($("#cars > option").length) { } // from eg below

Then simply prepend the All option if true like

$("#cars").prepend($('<option>', {
    value: 'All',
    text: 'All'
}));

Working Code

if ($("#cars > option").length) {
  // has children
  $("#cars").prepend($('<option>', {
    value: 'All',
    text: 'All'
  }));

} else {
  // empty
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="cars" id="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

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