Search code examples
javascriptjqueryjquery-select2jquery-select2-4

I'm unable to Capture Select2 Events - I suspect I'm using the wrong jquery selector


This is the javascript I've written - it alerts me that four .select2 instances were found and four select elements were found and logs a message to the console, but no amount of changing what I have selected from the select2 boxes is actually logging or alerting me about changes. I suspect I'm using the wrong selector for finding the objects to attach these change listeners to, but I can't find a complete example in the documentation for how to find my select2 elements.

$(document).on('change', '.select2-input', function(e) {
    console.log('Detected a different change!');
    alert('The other method of detecting changes worked!');
});
$('.select2').on('change', function(e) {
    console.log('Detected a change!');
    alert('Something was changed!');
});
console.log('Loaded!');
alert('Loaded v2 - found ' + $('.select2').length + ' instances of select2 and ' + $('select').length + ' instances of select.');

Solution

  • how to find my select2 elements

    This is the same selector that you use when you convert your select to a select2, eg:

    $('.my-select-dropdown').select2();
    

    I don't create the select2 instances

    In the case where the select2 is being generated elsewhere, you can find the original select that select2 has been applied to using:

    $(".select2-hidden-accessible")
    

    The key bit of info is that the events are raised against the original select dropdown rather than any of the select2 controls, example:

    // this happens elsewhere that you don't have control over
    $('.select2').select2();
    
    // find the original "converted" drop downs
    $('.select2-hidden-accessible').on('select2:select', function (e) {
        var data = e.params.data;
        console.log(data.id, data.text, $(".select2").val());
    });
    .select2 { width: 150px }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
    <script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
    
    <select class="select2">
      <option value="AL">Alabama</option>
      <option value="AK">Alaska</option>
      <option value="AZ">Arizona</option>
    </select>