jQuery Select2 onkeyup not firing
Asked Answered
B

3

8

I am trying to update the options of the Select2 input field with an AJAX call, but the onkeyup function linked to the input field does not run.

*Note that the onkeyup function does run when I set the multiple attribute of the select box as multiple="multiple", but when I try to get a single result like the select box by removing the attribute nothing happens

My HTML looks like this:

<select class="js-example-templating" style="width: 50%">
</select>

My jQuery looks like this:

ar all_options = [
    ['Alaskan/Hawaiian Time Zone', [['AK','Alaska'], ['HI','Hawaii']]],
    ['Pacific Time Zone', [['CA','California'], ['NV','Nevada'], ['OR','Oregon'], ['WA','Washington']]],
    ['Mountain Time Zone', [['CAAZ','Arizona'], ['CO','Colorado'], ['ID','Idaho'], ['MT','Montana'], ['NE','Nebraska'], ['NM','New Mexico'], ['ND','North Dakota'], ['UT','Utah'], ['WY','Wyoming']]]
];

function formatState(state) {
    if (!state.id) {
        return state.text;
    }
    var $state = $('<span><img src="vendor/images/flags/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>');
    return $state;
};

$(".js-example-templating").select2({
    minimumInputLength: 1,
    templateResult : formatState
});

$('.select2-search__field').on('keyup', function (e) {


    tmp_html = '';
    //do ajax call here

    $(all_options).each(function(i) {
        var group = all_options[i][0];
        var options = all_options[i][1];

        tmp_html += '<optgroup label="'+group+'">';

        console.log(options);

        $(options).each(function(i) {
            var option_id = options[i][0];
            var option_text = options[i][1];

            tmp_html += '<option value="'+option_id+'">'+option_text+'</option>';
        });

        tmp_html += '</optgroup>';  
    }); 

    //now add the new options to the select box

    $('.js-example-templating').html(tmp_html);
});  

The AJAX function has not been added, the onkeyup function at the moment just adds all the options, this will be added as soon as I can get the onkeyup function to run.

After this all the Select box is supposed to have the following options:

  <optgroup label="Alaskan/Hawaiian Time Zone">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Pacific Time Zone">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
  <optgroup label="Mountain Time Zone">
    <option value="AZ">Arizona</option>
    <option value="CO">Colorado</option>
    <option value="ID">Idaho</option>
    <option value="MT">Montana</option>
    <option value="NE">Nebraska</option>
    <option value="NM">New Mexico</option>
    <option value="ND">North Dakota</option>
    <option value="UT">Utah</option>
    <option value="WY">Wyoming</option>
  </optgroup>

Thanx in advance


EDIT

The input field gets added automatically when the Select2 initialization starts. The code for the input field look like this:

<input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox">

Here is a fiddle of what is happening: https://jsfiddle.net/Reckless/hz2vqzt7/

When you add the multiple="multiple" attribute and run again, it will update the available options, but without that it does not fire the onkeyup event

Brost answered 31/3, 2017 at 8:49 Comment(3)
where is the .select2-search__field elementGraber
The field gets added automatically when the Select2 initialization starts, I will add the input field code to the above questionBrost
the question has been updated with the code for the input fieldBrost
W
21

I think the problem is due to the .select2-search__field input being dynamically added to the page when the select2 is initialised, and it not hooking into the event handlers for the onkeyup function you've written.

I changed your function definition from:

$('.select2-search__field').on('keyup', function (e) {

to

$(document).on('keyup', '.select2-search__field', function (e) {    

and it seems to work just fine, without the multiple attribute being set.

See the altered fiddle here: Updated Fiddle

Werth answered 4/4, 2017 at 9:23 Comment(2)
Seems to be working :) I have however decided to go with Bootstrap's Typeahead. Was a bit more work to sort out than Select2, but looks and works greatBrost
how to use with multiselect option since when i am searching it working as expected but when i am selecting it .the select box is cleared !Nootka
A
0

Select2 creates a new element after the:

<select class="js-example-templating" style="width: 50%"></select>

You can add an event listener to the search field with this:

document.querySelector("#js-example-templating")
  .nextSibling.querySelector(".select2-search__field")
  .addEventListener("keyup", function () {
    alert("listener added");
  });
Acrid answered 25/2, 2022 at 12:1 Comment(0)
R
0

Instead of putting the eventListener on the '.select2-search__field', put in the element itself plus the data selector of select2. This shall make the keyup event work normally.

$("#elm").data("select2").on("keypress",function(evt) {
   console.log(evt)
})
Rate answered 29/8, 2023 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.