Autocomplete combobox widget force change - jquery-ui

I'm getting absolutely no where in getting the underlying select to fire a changed event after a autocomplete value is selected.
How can I force a change within the widget. From what I can find I need to
trigger a select event and trigger a change with something like this, but I can't get it to work
select: function(event,ui) {
this.value=ui.item.value;
$(this).trigger('change');
return false; }
(function( $ ) {
$.widget("st.comboboxAutocomplete", {
options: {
minLength: 0,
showDropdown: false,
width: '',
Id: '',
},
_create: function () {
this.wrapper = $("<span>")
.addClass("st-comboboxAutocomplete")
.css({ 'padding': '0px 0px', 'width': this.options.width})
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
if (this.options.showDropdown)
{
this._createShowAllButton();
}
},
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.attr("id", this.options.Id)
.addClass("st-comboboxAutocomplete-input")
.css('margin-right', '5px')
.autocomplete({
delay: 0,
minLength: this.options.minLength,
source: $.proxy(this, "_source"),
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.tooltip()
.css('background-color', '#fff')
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("st-comboboxAutocomplete-toggle ui-corner-right")
.on("mousedown", function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.on("click", function () {
input.trigger("focus");
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.autocomplete("instance").term = "";
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( "#combobox" ).comboboxAutocomplete();
$("#combobox").change(function() {
alert(this.value);
});
});
.ui-button { margin-left: -1px; }
.ui-button-icon-only .ui-button-text { padding: 0.35em; }
.ui-autocomplete-input { margin: 0; padding: 0.48em 0 0.47em 0.45em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<meta charset="utf-8">
<div class="demo">
<div class="ui-widget">
<label>Your preferred programming language: </label>
<select id="combobox">
<option value="">Select one...</option>
<option value="ActionScript">ActionScript</option>
<option value="AppleScript">AppleScript</option>
<option value="Asp">Asp</option>
<option value="BASIC">BASIC</option>
<option value="C">C</option>
<option value="C++">C++</option>
<option value="Clojure">Clojure</option>
<option value="COBOL">COBOL</option>
<option value="ColdFusion">ColdFusion</option>
<option value="Erlang">Erlang</option>
<option value="Fortran">Fortran</option>
<option value="Groovy">Groovy</option>
<option value="Haskell">Haskell</option>
<option value="Java">Java</option>
<option value="JavaScript">JavaScript</option>
<option value="Lisp">Lisp</option>
<option value="Perl">Perl</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
<option value="Ruby">Ruby</option>
<option value="Scala">Scala</option>
<option value="Scheme">Scheme</option>
</select>
</div>
<button id="toggle">Show underlying select</button>
</div><!-- End demo -->
<div class="demo-description">
<p>A custom widget built by composition of Autocomplete and Button. You can either type something into the field to get filtered suggestions based on your input, or use the button to get the full list of selections.</p>
<p>The input is read from an existing select-element for progressive enhancement, passed to Autocomplete with a customized source-option.</p>
</div><!-- End demo-description -->

In case inquiring minds want to know, I solved this with the following
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.attr("id", this.options.Id)
.addClass("st-comboboxAutocomplete-input")
.css('margin-right', '5px')
.autocomplete({
delay: 0,
minLength: this.options.minLength,
source: $.proxy(this, "_source"),
change: $.proxy(this, "_change")
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
}
_change: function (event, ui) {
this.value = ui.item.value;
this.element.trigger('change');
return false;
}
This will fire a change when you tab or exit the autocomplete. If you want it to fire the change on select then use
select: $.proxy(this, "_select")
_select: function (event, ui) {
this.element.trigger('change');
},

Related

C# razor select2 disable

Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});
You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.

Select2 custom data return from API

I am working with select2 to display the data return from the API. However, the data didn't manage to load out.Am I doing something wrong? Any ideas how to fix this?
HTML:
<select class="js-example-basic-single form-control select2 select2-hidden-accessible" id="user" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
script:
var url = "{{env('API_URL')}}";
var username = null;
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "jsonp",
method: "GET",
data: function (term) {
username = term.term;
return {"username": username};
},
url: url+"user/search/username?",
results: function (data) {
return {
results: data.result.users
};
},
},
formatResult: function (option) {
return "<option value='" + option.id + "'>" + option.username + "</option>";
},
formatSelection: function (option) {
return option.id;
}
});
result return from API:
result : [{"users":["[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})","[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})","[object] (App\\User: {\"username\":\"Alex\",\"id\":123458})","[object] (App\\User: {\"username\":\"Sky\",\"id\":1234569})","[object] (App\\User: {\"username\":\"Kvin\",\"id\":123460})"]}] []
One thing is your JSON return from API who is not well formatted.
[{
"users":[
"[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})",
"[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})",
...
]
}]
should be
[{
"users":[
{"username":"Kaki","id":123456}),
{"username":"(Alan)","id":123457}),
...
]
}]
I don't know what is Select2 version you use, but > 4 is advice.
Use functions templateResult and templateSelection is better, later you can return HTML for nicer rendering.
You can use this snipplet demo.
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>

How to determiine which dropdown was used

I have a form with more than one dropdown list, like this below. I can see how to get the ID's of each dropdown but I can't figure out how to get the one that was actually used. Would someone explain how to do that, please.
<div>
<select name="id[11]" class="pullDown" id="attrdrop0">
<option class="pink" value="31`">No</option>
<option class="pink" value="32">Yes (+$40.00)</option>
</select>
</div>
<div>
<select name="id[10]" class="pullDown" id="attrdrop1">
<option class="pink" value="31">No</option>
<option class="pink" value="32">Yes (+$150.00)</option>
</select>
</div>
<script>
$(function () {
$("#prices").change(function () {
console.log('A change was made');
CalculatePrice();
});
});
function CalculatePrice() {
var ttl_price = 0;
var id = '';
$(":input.select, :input").each(function() {
var cur_price = $('option:selected', $(this)).text();
ttl_price += cur_price;
id = $(this).attr('id');
/*** What now ***/
});
SetPrice(id, ttl_price);
}
</script>
You can pass the control as a parameter to CalculatePrice.
$(function () {
$("#prices").change(function () {
console.log('A change was made');
CalculatePrice(this);
});
});
function CalculatePrice(triggerObject) {
var ttl_price = 0;
var id = '';
$(":input.select, :input").each(function() {
var cur_price = $('option:selected', $(this)).text();
ttl_price += cur_price;
id = $(this).attr('id');
/*** What now ***/
if (triggerObject.id) {...}
});
SetPrice(id, ttl_price);
}
</script>

Select2 Dropdown autoselect if only 1 option available

I have a select2 dropdown box using remote datasource.
What I would like to do is if/when there is only one option returned by the search, auto select it. ie, the user doesn;t have to click on the option to make the selection.
$("#searchInfo_Entity_Key").select2({
ajax: {
url: "/Adjustment/GetEntity",
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
results: function (data) {
return { results: data };
},
},
initSelection: function (element, callback) {
var data = [];
callback(data);
},
minimumInputLength: 2,
allowClear: true,
placeholder: "Select an entity"
});
This is a custom matcher, that wraps around the default matcher and counts how many matches there are. If there is only one match, then it will select that match, change it, and close the dropdown box.
(Not tested with remote data.)
$(function() {
var matchCount = 0; // Track how many matches there are
var matched; // Track the ID of the last match
$('select').select2({
placeholder: 'Product Search',
allowClear: true,
matcher: function(params, data) {
// Wrap the default matcher that we have just overridden.
var match = $.fn.select2.defaults.defaults.matcher(params, data);
// If this is the first option that we are testing against,
// reset the matchCount to zero.
var first = $(data.element).closest('select').find('option').first().val();
if (first == data.id) matchCount = 0;
// If there was a match against this option, record it
if (match) {
matchCount = matchCount + 1;
matched = data.id;
}
// If this is the last option that we are testing against,
// now is a good time to check how many matches we had.
var last = $(data.element).closest('select').find('option').last().val();
if (last == data.id && matchCount == 1) {
// There was only one match, change the value to the
// matched option and close the dropdown box.
$(data.element).closest('select')
.val(matched).trigger('change')
.select2('close');
return null;
}
// Return the default match as normal. Null if no match.
return match;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select style="width: 20em">
<option value=""></option>
<option value="100">Product One</option>
<option value="200">Product Two</option>
<option value="300">Product Three</option>
<option value="400">Product Four</option>
<option value="500">Product Five</option>
</select>

Select2 with a checkbox list for a multiple select

I need to implement a select similar to this http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/
I want to use select2 for this, but I haven't been able to find anything from the creator of the select2 that would support this style of dropdown with checkboxes in it. Does anyone know a way to do this?
I've faced a similar need but was not able to find it.
The solution I've came across was using the flag closeOnSelect set to false
$("#yadayada").select2({closeOnSelect:false});
http://jsfiddle.net/jEADR/521/
Seems this is old post, but as it is very common issue, I`m posting this here.
I found that the author already added a plugin to select2 for this feature to have checkbox-like selection and the dropdown does not hide on click:
https://github.com/wasikuss/select2-multi-checkboxes
Example:
$('.select2-multiple').select2MultiCheckboxes({
placeholder: "Choose multiple elements",
})
http://jsfiddle.net/wasikuss/gx93rwnk/
All other features of select2 are preserved. There are few more predefined options set to work properly.
I managed to put something together, not perfect, but it works.
https://jsfiddle.net/Lkkm2L48/7/
jQuery(function($) {
$.fn.select2.amd.require([
'select2/selection/single',
'select2/selection/placeholder',
'select2/selection/allowClear',
'select2/dropdown',
'select2/dropdown/search',
'select2/dropdown/attachBody',
'select2/utils'
], function (SingleSelection, Placeholder, AllowClear, Dropdown, DropdownSearch, AttachBody, Utils) {
var SelectionAdapter = Utils.Decorate(
SingleSelection,
Placeholder
);
SelectionAdapter = Utils.Decorate(
SelectionAdapter,
AllowClear
);
var DropdownAdapter = Utils.Decorate(
Utils.Decorate(
Dropdown,
DropdownSearch
),
AttachBody
);
var base_element = $('.select2-multiple2')
$(base_element).select2({
placeholder: 'Select multiple items',
selectionAdapter: SelectionAdapter,
dropdownAdapter: DropdownAdapter,
allowClear: true,
templateResult: function (data) {
if (!data.id) { return data.text; }
var $res = $('<div></div>');
$res.text(data.text);
$res.addClass('wrap');
return $res;
},
templateSelection: function (data) {
if (!data.id) { return data.text; }
var selected = ($(base_element).val() || []).length;
var total = $('option', $(base_element)).length;
return "Selected " + selected + " of " + total;
}
})
});
});
CSS:
.select2-results__option .wrap:before{
font-family:fontAwesome;
color:#999;
content:"\f096";
width:25px;
height:25px;
padding-right: 10px;
}
.select2-results__option[aria-selected=true] .wrap:before{
content:"\f14a";
}
Add just two emoji with css
.select2-results__options {
&[aria-multiselectable=true] {
.select2-results__option {
&[aria-selected=true]:before {
content: '☑';
padding: 0 0 0 4px;
}
&:before {
content: '◻';
padding: 0 0 0 4px;
}
}
}
}
You see this sample a RTL select2 with emoji based checkbox
Here is very simple snippet, without strange modyfing of js - pure and simple css (with "Font Awesome")
$('.select2[multiple]').select2({
width: '100%',
closeOnSelect: false
})
#body{
padding: 30px
}
.select2-results__options[aria-multiselectable="true"] li {
padding-left: 30px;
position: relative
}
.select2-results__options[aria-multiselectable="true"] li:before {
position: absolute;
left: 8px;
opacity: .6;
top: 6px;
font-family: "FontAwesome";
content: "\f0c8";
}
.select2-results__options[aria-multiselectable="true"] li[aria-selected="true"]:before {
content: "\f14a";
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js"></script>
<div id="body">
<select name="fabric_color_en[]" id="fabric_color_en[]" multiple="multiple" class="form-control select2">
<option value="Beige">
Beige
</option>
<option value="Red">
Red
</option>
<option value="Petrol">
Petrol
</option>
<option value="Royal Blue">
Royal Blue
</option>
<option value="Dark Blue">
Dark Blue
</option>
<option value="Bottle Green">
Bottle Green
</option>
<option value="Light Grey">
Light Grey
</option>
</select>
</div>
Now the code is ready to use for you to implement the multiple checkboxes select2 dropdown.
Enjoy :)
//===============================================
//Start - Select 2 Multi-Select Code======================================================
var Select2MultiCheckBoxObj = [];
var id_selectElement = 'id_SelectElement';
var staticWordInID = 'state_';
function AddItemInSelect2MultiCheckBoxObj(id, IsChecked) {
if (Select2MultiCheckBoxObj.length > 0) {
let index = Select2MultiCheckBoxObj.findIndex(x => x.id == id);
if (index > -1) {
Select2MultiCheckBoxObj[index]["IsChecked"] = IsChecked;
}
else {
Select2MultiCheckBoxObj.push({ "id": id, "IsChecked": IsChecked });
}
}
else {
Select2MultiCheckBoxObj.push({ "id": id, "IsChecked": IsChecked });
}
}
function IsCheckedAllOption(trueOrFalse) {
$.map($('#' + id_selectElement + ' option'), function (option) {
AddItemInSelect2MultiCheckBoxObj(option.value, trueOrFalse);
});
$('#' + id_selectElement + " > option").not(':first').prop("selected", trueOrFalse); //This will select all options and adds in Select2
$("#" + id_selectElement).trigger("change");//This will effect the changes
$(".select2-results__option").not(':first').attr("aria-selected", trueOrFalse); //This will make grey color of selected options
$("input[id^='" + staticWordInID + "']").prop("checked", trueOrFalse);
}
$(document).ready(function () {
//Begin - Select 2 Multi-Select Code
$.map($('#' + id_selectElement + ' option'), function (option) {
AddItemInSelect2MultiCheckBoxObj(option.value, false);
});
function formatResult(state) {
if (Select2MultiCheckBoxObj.length > 0) {
var stateId = staticWordInID + state.id;
let index = Select2MultiCheckBoxObj.findIndex(x => x.id == state.id);
if (index > -1) {
var checkbox = $('<div class="checkbox"><input class="select2Checkbox" id="' + stateId + '" type="checkbox" ' + (Select2MultiCheckBoxObj[index]["IsChecked"] ? 'checked' : '') +
'><label for="checkbox' + stateId + '">' + state.text + '</label></div>', { id: stateId });
return checkbox;
}
}
}
let optionSelect2 = {
templateResult: formatResult,
closeOnSelect: false,
width: '100%'
};
let $select2 = $("#" + id_selectElement).select2(optionSelect2);
//var scrollTop;
//$select2.on("select2:selecting", function (event) {
// var $pr = $('#' + event.params.args.data._resultId).parent();
// scrollTop = $pr.prop('scrollTop');
// let xxxx = 2;
//});
$select2.on("select2:select", function (event) {
$("#" + staticWordInID + event.params.data.id).prop("checked", true);
AddItemInSelect2MultiCheckBoxObj(event.params.data.id, true);
//If all options are slected then selectAll option would be also selected.
if (Select2MultiCheckBoxObj.filter(x => x.IsChecked === false).length === 1) {
AddItemInSelect2MultiCheckBoxObj(0, true);
$("#" + staticWordInID + "0").prop("checked", true);
}
});
$select2.on("select2:unselect", function (event) {
$("#" + staticWordInID + "0").prop("checked", false);
AddItemInSelect2MultiCheckBoxObj(0, false);
$("#" + staticWordInID + event.params.data.id).prop("checked", false);
AddItemInSelect2MultiCheckBoxObj(event.params.data.id, false);
});
$(document).on("click", "#" + staticWordInID + "0", function () {
//var b = !($("#state_SelectAll").is(':checked'));
var b = $("#" + staticWordInID + "0").is(':checked');
IsCheckedAllOption(b);
//state_CheckAll = b;
//$(window).scroll();
});
$(document).on("click", ".select2Checkbox", function (event) {
let selector = "#" + this.id;
let isChecked = Select2MultiCheckBoxObj[Select2MultiCheckBoxObj.findIndex(x => x.id == this.id.replaceAll(staticWordInID, ''))]['IsChecked'];
$(selector).prop("checked", isChecked);
});
});
//====End - Select 2 Multi-Select Code==
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="undefined" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="container-fluid">
<hr/>
<p>Here, you can select any item by clicking on row or checked in on checkbox and can unselect in reverse way.</p>
<p>But I didn't give the option to select "SelectAll" option by clicking on his row, you can select-all and unselect-all by click on checkbox only rather than row.</p>
<div class="row" style="width:50%">
<label for="id_SelectElement" class="col-sm-2">Part Name: </label>
<div class="col-sm-4">
<select id="id_SelectElement" placeholder="Select Text" multiple>
<option value="0" disabled>Select All</option>
<option value="11">Php</option>
<option value="22">Bootstrap</option>
<option value="33">sql</option>
<option value="44">Node Js</option>
<option value="55">Laravel</option>
<option value="66">Jquery</option>
<option value="77">React</option>
<option value="88">Vew.JS</option>
<option value="99">MVC</option>
<option value="10">DotNetCore</option>
<option value="12">Java</option>
<option value="13">Artifical Intiligence</option>
<option value="14">Data Structure</option>
<option value="15">Data Science</option>
<option value="16">Robotics</option>
<option value="17">Node Js 2</option>
<option value="18">Laravel 23</option>
<option value="19">Jquery 3.4</option>
</select>
</div>
</div>
</div>
Another workaround is to "prepend" checkbox icons using CSS. I use bootstrap theme - your select2-container may be different.
.select2-container--bootstrap .select2-results__option[aria-selected=true]:before { content:'\e067 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }
.select2-container--bootstrap .select2-results__option:before { content:'\e157 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }

Resources