1$(".class").select2({
2 templateResult: formatState,
3 templateSelection: formatState
4});
5
6function formatState (opt) {
7 if (!opt.id) {
8 return opt.text.toUpperCase();
9 }
10
11 var optimage = $(opt.element).attr('data-image');
12 console.log(optimage)
13 if(!optimage){
14 return opt.text.toUpperCase();
15 } else {
16 var $opt = $(
17 '<span><img src="' + optimage + '" width="60px" /> ' + opt.text.toUpperCase() + '</span>'
18 );
19 return $opt;
20 }
21};
22
1$('#element').select2({
2 placeholder: 'Select a option',
3 minimumInputLength: 3,
4 ajax: {
5 url: route('api.fetch-options'),
6 dataType: 'json',
7 type: 'GET',
8 quietMillis: 50,
9 data: function (params) {
10 return {
11 visitor_name: params.term
12 }
13 },
14 processResults({ data }) {
15 return {
16 results: $.map(data, function (item) {
17 return {
18 text: item.name,
19 id: item.id,
20 }
21 })
22 }
23 }
24 }
25}).change(() => {
26 // perform some action on change
27});
1var initQuantitiesDropdown = function () {
2 var options = [];
3 var selectedFruit = $("#fruits").val();
4 $.each(pageData.products[selectedFruit].quantities, function (key, value) {
5 options.push({
6 text: value,
7 id: key
8 });
9 })
10 $("#quantities").empty().select2({
11 data: options
12 });
13};
14
15$("#fruits").select2().change(initQuantitiesDropdown);
16initQuantitiesDropdown();
1//Installation
2<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
3<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
4
5
6
7// In your Javascript (external .js resource or <script> tag)
8$(document).ready(function() {
9 $('.js-example-basic-single').select2();
10});