0

I am using Select2 plugin as below:

JS

function initAssignmentsAjax() {

        $("#assignments").empty();

        $( "#assignments" ).select2( {
            placeholder: "Select an assignment",
            allowClear: true,

            ajax: {
                url: "/Home/GetAssignments",
                dataType: 'json',
                delay: 250,
                data: function ( params ) {
                    return {
                        q: params.term, // search term
                        page: params.page
                    };
                },

                processResults: processAssignmentsResult,

                cache: true
            },
            escapeMarkup: function ( markup ) { return markup; }, // let our custom formatter work    TUTAJ WCHODZI PO assignmentsTemplateSelectionHandler
            minimumInputLength: 3, //1
            templateSelection: assignmentsTemplateSelectionHandler,
            templateResult: assignmentsTemplateResultHandler
        } )
    }

    function processAssignmentsResult(data, params) {

        var json = JSON.parse( data.Data );
        var x = $.map( json, function ( item ) {
            return {
                text: item.ProjectNumber + ' : ' + item.BatchName,
                children: item.ChildItems,
            };
        } )

        return { results: x };
    }

HTML

<select id="assignments" style="width: 500px;" ></select>

It works fine when I am typing values from UI - it sends Ajax query to controller and on the end presents values in control.

I have added also below function ( based on How to programmatically inject search queries into Select2 v4? ) to programaticly enter value to search

function selectAssignments( term ) {

    $( "#assignments" ).empty();

    var assignmentElementControl = $( "#assignments" );

    assignmentElementControl.select2( 'open' );

    // Get the search box within the dropdown or the selection
    // Dropdown = single, Selection = multiple
    var $search = assignmentElementControl.data( 'select2' ).dropdown.$search || assignmentElementControl.data( 'select2' ).selection.$search;
    // This is undocumented and may change in the future

    $search.val( term );
    $search.trigger( 'keyup' );
}

When I reload page and using this function from browser console ( or bind it to some button in UI ) it also works fine. But it stop to work when I first try to search by typing in Select2 control ( this pass ) but then when I try to use this function it does not run ajax search query from Select2 control ( it open searching list, show entered query, but not fire ajax ). So what using Select2 UI searching break this function to work ?

Community
  • 1
  • 1
user3057544
  • 807
  • 9
  • 22

1 Answers1

0

In your function selectAssignments() try to trigger the change of the select2:

$search.val( term );
$search.trigger( 'keyup' );
$search.trigger( 'change' ); //Here
Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52