Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
Cómo saber si un select2 tiene opciones

No necesito saber si tiene opciones seleccionadas, solo necesito saber si tiene opciones disponibles. En caso de que tenga una o más opciones, quiero agregar manualmente otra opción que sea “todas”. Y por defecto está seleccionado.

He visto que en internet se usa lo siguiente, pero lo he probado y siempre me da 1. No importa si hay 2 opciones, 1 o ninguna.

 $('#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

Naturalmente, he cambiado el identificador por el mío.

¿Alguien sabría como hacerlo?

Gracias por adelantado

Mi código es este:

 $("#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') }}'; } } });

Pero cuando pongo

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

devuelve 1 siempre, cuando tengo 0 o 1 o 2 opciones.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use $("#myselect > option").length para verificar si hay options(children) ,

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

Luego simplemente anteponga la opción Todo si es true como

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

Código de trabajo

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!