LeftyX LeftyX - 5 months ago 21
Javascript Question

select2 and remote data: pre-set value and text avoiding server round-trip

I am generating my HTML tags server-side (asp.net mvc4).

I would like to pre-set the value and the description of my HIDDEN field avoiding the ajax call to fetch the data in the

initSelection
function.

I've seen someone setting the values using javascript:

$("#select2Test").select2('data', { id: 20832, text: 'LONDON' })


but still it would require me extra-code to achieve something that has been already streamed from the server in a viewmodel.

I've come up with something like this:

<input type="hidden" id="select2Test" name="select2Test" value="20832" data-option="LONDON" />


I've used an HTML5 data attribute
data-option
with the description of my lookup and I've implemented the initSelection function so that I can read the value of my field and it's data attribute:

initSelection: function (item, callback) {
var id = item.val();
var text = item.data('option');
var data = { id: id, text: text };
callback(data);
},


I've seen that initSelection is called only when the hidden field has a value set.

Everything seems to work properly.

Are there any better options?

Answer

data-option combined with a custom initSelection did the trick.

    $("#lookup_id").select2({
        minimumInputLength: 3,
        multiple: false,
        allowClear: true,
        ajax: {
            url: urlFetchCity,
            dataType: 'json',
            type: "POST",
            data: function (term, page) { return { city: term }; },
            results: function (data, page) {
                return {
                    return {results: data};
                };
            }
        },
        initSelection: function (item, callback) {
            var id = item.val();
            var text = item.data('option');
            var data = { id: id, text: text };
            callback(data);
        },
        formatResult: function (item) { return ('<div>' + item.id + ' - ' + item.text + '</div>'); },
        formatSelection: function (item) { return (item.text); },
        escapeMarkup: function (m) { return m; }
    });

for those who are interested I've created a GitHub repository where you can find an ASP.NET MVC4 project in which I've added an html helper to create a select2 tags with all the features for client-side validation.

Comments