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 > 0Naturalmente, 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.
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>