'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.



Solution 1:[1]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tushar