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

1

5

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?

Familial answered 16/5, 2013 at 16:50 Comment(2)
What are you doing exactly in the callback? Wouldn't it be better to load that data as well upon loading the page?Iridissa
@Kenneth: I've updated my question. There's the full code there. The page is loaded already. My controller returns a view and a viewmodel with the entire dataset.Familial
F
14

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.

Familial answered 29/5, 2013 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.