select2 set option attributes manually for each option - javascript

i have select2 dropdown like:
<select class="form-control validateblank txtSelectChallan" id="txtSelectChallan" />
and i am setting dropdown data by ajax call like:
$.ajax({
type: "POST",
url: "/Account/MaterialSheet.aspx/GetMaterialSheetByLedgerId",
data: '{LedgerId: "' + AccId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.Result == "OK") {
var challanresults = [];
$.each(data.d.Records, function (index, challn) {
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
});
eachtr.find('.txtSelectChallan').select2({
placeholder: "Select Challan",
data: challanresults,
multiple: true
});
swal.close();
challanresults = null;
}
},
error: function (err) {
swal(
'Oops...',
'Error occured while retrieving data',
'error'
);
}
});
and i get dropdown like :
<select class="form-control validateblank txtSelectChallan select2 hidden-accessible" id="txtSelectChallan" tabindex="-1" aria-hidden="true" multiple="">
<option value="1006">123123</option>
<option value="1007">32123</option>
i have tried to set option attribute using:
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
but i cant get amout as option attribute any idea how to set custom attribute for all option in select2?

Try like this inside foreach loop, and set the trigger after that.
var data = {
id: challn.MaterialSheet_ID,
text: challn.Challan_No
};
var newOption = new Option(data.text, data.id, false, false);
$('#txtSelectChallan').append(newOption).trigger('change');
Check this link for further solution on custom attributes
Or Simply you can do like this in a loop for the result set
var option = "<option value="+challn.MaterialSheet_ID+" amount="+challn.Total_Amount+">"+challn.Challan_No+"</option>
This is what Select2 Official Site has to say about custom-data-fields
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
Click here for the above reference link

Related

select2 not displaying selected value text added programatically

I have a dropdown created with select2 (v4.0.13 and I can not change it) using AJAX requests on a form where the user can search for things. The page is built with Thymeleaf and when the view is reloaded the dropdown value is lost.
Following the recommendation of the documentation itself when you deal with AJAX values, I have writed this code:
let selectedOption = $('#select2-id');
$.ajax({
type: 'GET',
dataType: 'json',
url: baseAjaxUrl + '/api_endpoint?q=' + myVar,
}).then(function (data) {
if (data.length !== 0) {
let optionValues = data[0];
let option = new Option(optionValues.name, optionValues.id, true, true);
selectedOption.append(option).trigger('change.select2');
selectedOption.trigger({
type: 'select2:select',
params: {data: optionValues}
});
}
});
Now, when the view is reloaded the dropdown has the value but does not show its text. An x appears to remove it and if you hover the mouse over it in the tooltip the text that should be displayed in the dropdown appears.
In the <span> generated by select2 I can see the title attribute with the value that should be displayed:
<span class="select2-selection__rendered" id="select2-anId-container" role="textbox" aria-readonly="true" title="The text that should be displayed">
<span class="select2-selection__clear" title="Remove all items" data-select2-id="20">×</span>
</span>
The select2 is initialised as follows:
$('#select2-id').select2({
ajax: {
url: baseAjaxUrl + '/api_endpoint',
dataType: 'json',
delay: 180,
data: function (parameters) {
return {
q: parameters.term,
page: parameters.page
};
},
processResults: function (data, page) {
return {
results: data
};
}
},
placeholder: {
id: "-1",
text: "Select an item"
},
allowClear: true,
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 5,
templateResult: formatItem,
templateSelection: formatItemSelection,
theme: "bootstrap",
width: myCustomWidth
});
What is the problem or what have I done wrong?
Greetings.
After finding this answer, my problem was that when selecting an option, templateSelection is used. Checking the function I realised that the object I receive has the fields id and name. The object that handles select2 also has the fields id and name but it has another one, text, and this is the one it uses to show the value!
So in the function I use for templateSelection I have to do:
if (data.text === "") {
data.text = data.name;
}
... other stuff ...
return data.text;
Done!

select2 add custom classes using processResults

I used to add custom classes and use it to fill an input according to the selection
since I did it directly in the view
example:
<option value="290044" data-nombre="xxxx" data-select2-id="20">0931105/Diego Suarez</option>
but since I had to bring more than 70000 records I do it now from the server side and I don't know how to add the custom classes that I want to appear
it appears like this automatically
example
<option value="290044" (here i want to add my custom class) data-select2-id="20">09311055/Diego Suarez</option>
I attach the complete code
$(document).ready(function () {
$("#cliente").select2({
language: "es",
minimumInputLength: 2,
ajax: {
url: "/Clientes/jsonclientes",
dataType: "json",
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.NIF20 + "/" + item.NOMBRECLIENTE,
id: item.CODCLIENTE,
};
}),
};
},
cache: true,
},
});
$("#cliente").change(function () {
let selected = $(this).find("option:selected");
direccion = selected.data("direccion");
$("#direccione").val(direccion);
});
})

Select2 ajax: preselected data in edit mode

I'm making user profile page on Laravel and using select2 component to filter huge list of items.
I have a ajax-based select2. It's good when you are on /create page, but I need to have selected value in it, when I am on page /edit/1.
$('.search-filter-ajax').select2({
width: '100%',
minimumInputLength: 3,
placeholder: "Search...",
ajax: {
url: '/api/listing/search/',
data: function (term) {
return {
data: term.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
search_from: item.name,
model: 'some_model',
id: item.id
}
})
};
},
dataType: 'json',
type: "GET",
delay: 250,
},
});
I tried to use initSelection function, but no luck, because it creates only select2 text elements, when I need real <option value="1"> something </option> component.
initSelection: function (element, callback) {
var id = $(element).data('select-id');
var text = $(element).data('select-text');
callback({ id: id, text: text });
},
How can I have a valid preselected option in select2 on page load, but still having opportunity to fire ajax call by onChange?
well, you could try to use your own logic to generate slect options like
$.ajax().then((res)=>{
$('#select').html('');
res.data.forEach((item)={$('#select').append($('option').text(item.text).value(item.value);)})
})

Append selected after ajax call

I have a Select 2 drop down search function. I am trying to load the results from an ajax call as the selected/default values. I am not sure where I am going wrong? What is the syntax I need to change here so that when I click my modal it shows results preset.
$(document).ready(function() {
$('.editApptModal-button').click(function() {
var appointmentID = $(this).attr('data-appointmentID');
$('#editApptModal').find('input[name="appointmentID"]').val(appointmentID);
$.ajax({
type: 'ajax',
method: 'get',
url: '/ajax',
async: false,
dataType: 'json',
success: function(response) {
console.log(JSON.stringify(response));
$.each(response.employees.data, function(key, value) {
$('select').append($("<option selected></option>",
//<HERE Selected is not working.
//If I remove selected results load in dropdown
{
value: value.id,
text: value.name
}));
});
$('#editApptModal').modal('show');
},
error: function(response) {
alert('Could not displaying data' + response);
}
});
$('#editApptModal').modal('show');
});
});
<select multiple="multiple" name="employees[]" id="form-field-select-4" class="form-control search-select">
<option selected value=""></option>
First you should try to append only once because it's an heavy operation.
And by setting attributes directly seems to work here.
var datas = [
{value: 'toto', text: 'Toto'},
{value: 'titi', text: 'Titi'}
];
var options = '';
$.each(datas, function(key, value) {
options += '<option selected>'+value.text+'</option>';
});
$('#select').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select"></select>
You have to issue the refresh command after you are done. Here a quick snippet of it working doing the same thing for one of my projects. TransportRecord_TransportCarrierID is the ID for my select element.
$('#TransportRecord_TransportCarrierID').empty();
$.each(jsonResponse, function (key, item) {
var option = $('<option selected>').text(item.Text).val(item.Value);
$('#TransportRecord_TransportCarrierID').append(option);
});
$('#TransportRecord_TransportCarrierID').selectpicker('refresh');
Html
<select class="form-control selectpicker" data-live-search="true" data-style="btn-defaultWhite" multiple="multiple" id="TransportRecord_TransportCarrierID" name="TransportRecord.TransportCarrierID">//your initial options</select>

How to set Select2 value using initSelection?

I am using jQuery Select2 for dropdown lists. The data is loading via AJAX call using in JSON format.
Here is my script:
$("#sub_lessons").select2({
maximumSelectionSize: 1,
placeholder: "Select Sublessons",
allowClear: true,
multiple:true,
ajax: {
url: "getData.action?lid="+lessonid,
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
My html snippet:
<input type="hidden" id="sub_lessons" style="width:300px"/>
When we clicking on the select2 box the data is loading perfectly,
but I have the function like setValue() when button is clicked.
<input type="button" onclick="setValue(1)"/>
And my function is:
function setValue(no)
{
$('#sub_lessons').select2('val',no);
}
But the value is not being set. I searched in some sites and suggested to use initselection.I used initselection,but it does not work.please help me how to set value to select2 when button is pressed.
any help would be appreciated.
try something like this
$('#sub_lessons').select2('val','no');
I try this; work for me. You should add this to initSelection select2:
initSelection: function (element, callback) {
var id = $(element).val();
$.ajax("url/" + id, {
dataType: "json"
}).done(function (data) {
var newOption = new Option(data.title, data.id, true, true);
$('#sub_lessons').append(newOption).trigger('change');
callback({"text": data.title, "id": data.id});
});
},

Categories