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?