steveareeno
steveareeno

Reputation: 1977

populate jquery select2 with original value

I am using the select2 plugin as an autocomplete for a text box. The autocomplete makes an ajax call to an employee view in a database. Everything is working great except when the user opens the webform to edit a record. I need the select2 control to load the value originally saved with the record regardless of whether it exists in the list or not. When I open the edit form, the select2 control is blank. I know I can probably load the value if it is in the json data return from the ajax call, but what if it's not? I can see the value in the initSelection but I don't know how to set the controls text/value to it.

Long story short, the view I am making the ajax call to may or may not have the original employee value in it. For example, if an employee was originally selected from the view but left for another branch/agency, the view would no longer show them. I still need to display the original value in the control. Hope that makes sense. Here is what I have for code. I can see the original value in the initSelection but don't know how to get it in the control:

    var URL = '@Url.Action("GetEmployees", "AssetAssignment")';
    var originalValue = "";

    $('#AssignedTo').select2({
        placeholder: "Type an MJB employee name or county...",
        minimumInputLength: 3,
        ajax: {
            url: URL,
            dataType: 'json',
            type: "GET",
            quietMillis: 50,
            data: function (term) {
                return { term: term };
            },
            results: function (data) {
                return { results: data.data };
            }
        },
        id: function (object) {
            // store the text vs the id
            return object.text;
        },       
        createSearchChoice: function (term, data) {
            //Allow manually entered text in drop down.
            if ( $(data).filter( function() {
              return this.text.localeCompare(term)===0;
            }).length===0) {
                return { id: "", text: term, county: "" };
            }
        },
        initSelection: function (element, callback) {
            var id = $(element).val();
            if (id !== "") {
                //var id = element.val();
                //var text = element.data('option');
                //var data = { id: id, text: text };
                //callback(data);
                //alert(JSON.stringify(data))
                originalValue = id;
            }
        },
        formatResult: employeeFormatResult,
        formatSelection: employeeFormatSelection
    });

    // get other values from the selected item and put them in the appropriate controls
    $('#AssignedTo').change(function () {
        var id = $('#AssignedTo').select2('data').id;
        var county = $('#AssignedTo').select2('data').county;
        $('#AssignedToEmployeeId').val(id);
        $('#AssignedToEmployeeCounty').val(county);
    });

});

function employeeFormatResult(data) {
    var markup = "<table class='select2-result'><tr>";
    markup += "<td class='select2-result-id'>" + $.trim(data.id) + "</td>";
    markup += "<td class='select2-result-text'>" + data.text + "</td>";
    markup += "<td class='select2-result-county'>" + data.county + "</td>";
    markup += "</tr></table>";
    return markup;
}

function employeeFormatSelection(data) {
    return data.text;
}

Upvotes: 1

Views: 4850

Answers (2)

Joe Blank
Joe Blank

Reputation: 1

ATTENTION, this is the correct usage According to

https://select2.github.io/examples.html

$(".js-example-data-array-selected").select2({
  data: data
})

select2 (current version).

Upvotes: 0

steveareeno
steveareeno

Reputation: 1977

It figures. I have been working on this for more than a day and a half and five minutes after I post the question I figure it out. I have to set the value with:

if (originalValue.length > 0)
    $("#AssignedTo").select2("data", { id: originalValue, text: originalValue }); 

This works for me because I don't care if the original value matches anything returned by the ajax call.

Upvotes: 1

Related Questions