I have the following html code:
<div class='multiWrapper'>
<select id="multi" class="js-dropdown-from-code">
<optgroup class='def-cursor' label='Code' data-city='Description'>
<option data-city="" data-id="0">Select unit...</option>
<option data-city="New York" data-id="1">USA</option>
<option data-city="London" data-id="2">UK</option>
</optgroup>
</select>
</div>
Where the select is converted into a Select2 dropdown list with two columns.
$('#multi').select2({
width: '100%',
formatResult: formatResultMulti,
dropdownCssClass: 'bigdrop'
});
Using this functionality.
function formatResultMulti(data) {
var city = $(data.element).data('city');
var classAttr = $(data.element).attr('class');
var hasClass = typeof classAttr != 'undefined';
classAttr = hasClass ? ' ' + classAttr : '';
var $result = $(
'<div class="row" style="font-size: 0.8125rem;">' +
'<div class="col-md-6 col-xs-6' + classAttr + '">' + data.text + '</div>' +
'<div class="col-md-6 col-xs-6' + classAttr + '">' + city + '</div>' +
'</div>'
);
return $result;
}
All of this is working, my question is when I am trying to load the select2 with a specific value to start.
Normally I would use the $('#multi).val('').trigger('change') to set the value, but as i am using an option group, i am not sure on how to do the same.
Can anyone please rescue me from my ignorance.
UPDATE:
I have added the missing HTML option tags. As you can see I am not using the value tag, but a data attribute data-id.
I have found that using the following works
$("#multi option[data-id='30']").prop("selected", true).trigger('change');
but it is not setting the underlying values, so on submitting the form, validation is not recognising the change trigger.
value='<something>'set? etc. - Jason Roman