jQuery addClass example

Change class name on click in jQuery

by dont_panic

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css">
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<select id="tag_list">
</select>

CSS

select {
    width: 100%;
}

JavaScript

$(document).ready(function(){

    // JSfiddle can simulate AJAX requests, we just tell it what data AJAX should return.
    // Use your sample data for that.
    var json='[{"id": "5","text": "laravel3"},{"id": "4","text": "laravel2"}]';

    $('#tag_list').select2({
        placeholder: "Choose tags...",
        tags: true,
        minimumInputLength: 3,
        tokenSeparators: [",", " "],
        createSearchChoice: function(term, data) {
            if ($(data).filter(function() {
                return this.text.localeCompare(term) === 0;
            }).length === 0) {
                return {
                    id: term,
                    text: term
                };
            }
        },
        ajax: {
        	type: 'post',           // This is how JSFiddle simulates AJAX, must use POST
            url: '/echo/json',		// This is how JSFiddle simulates AJAX
            dataType: 'json',
            data: function (params) {
                return {
                    q: $.trim(params.term),
                    json: json		// This is how JSFiddle simulates AJAX, json will be the response
                };
            },
            processResults: function (data) {
            	console.dir(data);
                return {
                	// Transform data, use text as id
                    results: $.map(data, function (obj) {
                        obj.id = obj.text;
                        return obj;
                    })
                };
            },
            delay: 250,
            cache: true
        }
    });
});