How to prevent select2 to call select2:close the second time when selectOnClose is set to true? - jquery-select2

I am using Select2 V. 4.0.10
I want to have a select2 that behaves the same way when you select using the Enter key and the Tab key.
What happens is that when selecting using the Tab key, the close event is called twice, which is not what was intended to do.
var data = [
{ id: 0, text: 'New' },
{ id: 1, text: 'In Process' },
{ id: 2, text: 'Draft' },
{ id: 3, text: 'Submitted' },
{ id: 4, text: 'Deleted' }
];
$(".test").select2({
allowClear: true,
selectOnClose: true,
data: data,
placeholder: "Select a status"
});
$("select.test", "body").off("select2:close").on("select2:close", function (e){
// This is called twice
console.log("select2:close");
});
select.test {
width: 200px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/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://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<select class="test"></select>
Here are the sequences of the select2 events that are triggered when selecting with the Tab/Enter key.
TAB
select2:opening
select2:open
select2:closing
select2:selecting
change
change.select
select2:closing
select2:close
select2:select
select2:close
ENTER
select2:opening
select2:open
select2:selecting
change
change.select
select2:closing
select2:close
select2:select

As the pattern in always the same, the solution was to create a variable that would be toggled on when select2:select was triggered, and use that to see if it was be used before.
Notice, instead of using the global window object you should rather use a class variable or a prototype property to store this boolean.
var data = [
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' },
{ id: 2, text: 'duplicate' },
{ id: 3, text: 'invalid' },
{ id: 4, text: 'wontfix' }
];
window._select2Select = false;
$(document).on('select2:select', "select", function (e) {
window._select2Select = true;
});
$(".test").select2({
allowClear: true,
selectOnClose: true,
data: data,
placeholder: "Select a status"
});
$("select.test", "body")
.off("select2:close")
.on("select2:close", function(e) {
if(window._select2Select){
window._select2Select = false;
return;
}
console.log("select2:close");
window._select2Select = false;
});

Related

filter the ui grid value based on the row check box is selected

This is the ui grid code( minimal)
//js file
vm.gridOptions1 = {
enableColumnResizing: true,
enableAutoResizing: false,
columnDefs: [
{
field: 'createdDate',
displayName: 'Created Date',
type: 'date',
cellFilter: 'date:"dd-MM-yyyy"',
enableHiding: false, headerTooltip: 'Created Date'
},{
name: 'Refer',
displayName: 'Refer', enableSorting: false, headerTooltip: 'Refer',
cellTemplate: '<input type="checkbox" ng-model="row.entity.isReferred" />'
}
]});
On click of this byutton I need to filter, get only rows which check box is selected(isReferred = true)
//html file
<button type="button" class="btn btn-primary-joli " ng-click="srchctrl.send">Send</button>
This is the file trying to get the filtered list based on the redeffered check box value, but its not working.
//JS file
vm.send = function () {
if (vm.gridApi.selection.data != null && vm.gridApi.selection.data != undefined) {
vm.referredList = filterFilter(vm.gridApi.selection.data, {
isReferred: true
});
console.log("referredList :"+JSON.stringify(referredList));
}
};
How can I get all the value ticked. I don't want to invoke method on each click event on check box.
I think the easiest way to achieve this is by using the gridApi.grid.registerRowsProcessor function. I have adapted a Plunker to show what I mean:
http://plnkr.co/edit/lyXcb90yQ0ErUJnSH7yF
Apps.js:
var app = angular.module('plunker', ['ui.grid']);
app.controller('MainCtrl', ['$scope', 'uiGridConstants', function($scope, uiGridConstants) {
$scope.gridOptions = {
columnDefs: [
{field: 'col1', displayName: 'Column 1', width: 175},
{field: 'col2', displayName: 'isReferred', width: '*'}
],
data: [
{ col1: "Hello 1",col2: true},
{ col1: "Hello 2", col2: false},
{ col1: "Hello 3", col2: true},
{ col1: "Hello 4", col2: false},
{ col1: "Hello 5", col2: true}
],
enableFiltering: true,
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
}
};
$scope.Filter = Filter;
$scope.ShowAll = ShowAll;
function ShowAll() {
$scope.gridApi.grid.removeRowsProcessor(myFilter);
$scope.gridApi.core.queueGridRefresh();
}
function Filter() {
$scope.gridApi.grid.registerRowsProcessor(myFilter, 150);
$scope.gridApi.core.queueGridRefresh();
}
function myFilter(renderableRows) {
renderableRows.forEach( function(row) {
row.visible = row.entity.col2;
});
return renderableRows;
}
}]);
Clicking the Filter button will register the myFilter RowsProcessor, which will iterate through all rows to alter the visible attribute.
Clicking the ShowAll button will remove the RowsProcessor, thus showing all previously hidden rows again.
Whenever an isReferred value changes, the filter will cause the grid to automatically update this change.

jquery select2 return json result name

I am new in jquery select2, in result return id, text and name where id is value I know how to get return id(value) with x$("inputBox").val();. but I want get return name in jquery-select2.
Is there any method to get the return name?
x$("#{id:city_combo_box}").select2({
placeholder:"Select City",
allowClear:true,
minimuminputLength:2,
templateResult: formatRepo,
escapeMarkup: function (markup) {return markup},
templateSelection: formatRepoSelection,
multiple:false,
ajax: {
url:ajaxurl,
dataType:"json",
data: function(params){
pp = params.term;
return{
startKey: pp,
page: params.page,
count: 10
};
},
processResults: function (data, params){
var k = data.viewentry;
console.log(k);
params.page = params.page;
return {
results: $.map(k, function(obj) {
return {id: (obj.entrydata[1].text[0]), text: obj.entrydata, name: (obj.entrydata[0].text[0])};
})
};
}
}
}).on("change", function(e){ x$("#{id:claim_limit_text}").val(x$("#{id:city_combo_box}").val(id));
}).trigger("change");
})
The only solution I came across is this:
html
<div id="ddWrapper1">
<select id="dd1"></select>
</div>
js
$(document).ready(function() {
var ddDate = [{
id: 1,
text: 'some item'
}, {
id: 2,
text: 'even more items'
}, {
id: 3,
text: 'oh no'
}, {
id: 4,
text: 'that is a realy long item name...'
}];
$('#dd1').select2({
data: ddDate,
allowClear: true,
multiple: true,
placeholder: '[dd1] select some items'
});
$('#dd1').on('change', function() {
console.log($('#dd1').data('select2').$selection[0].innerText);
})
});
But I have to admit that the result is not the nicest.

Filter by id as well as text in Select2

var data = [{ id: 11-07, text: 'enhancement' }, { id: 11-04, text: 'bug' },
{ id: 11-08, text: 'duplicate' }, { id: 11-09, text: 'invalid' },
{ id: 11-10, text: 'wontfix' }];
$(".js-example-data-array").select2({
data: data
})
<select class="js-example-data-array"></select>
I want to filter the select2 with both id as well as text. By default , it filters by text.
How can I filter by id as well?
You must use "matcher".
$(".js-example-data-array").select2({
data: data,
matcher: function(term, text, option) {
return text.toUpperCase().indexOf(term.toUpperCase())>=0 || option.val().toUpperCase().indexOf(term.toUpperCase())>=0;
}
})
It will return result filtered by text or id.
Use a a custom matcher. Add a property "matcher" with an custom function so you can match it your self. For explanation check the examples page.
To match against the id you need to use a 'complex matcher'. More info about that can be found here.
For the current 4th version the function for the matcher must be written differently. This code is based on an example from the documentation:
$(document).ready(function() {
var data = [{ id: '11-07', text: 'enhancement' }, { id: '11-04', text: 'bug' },
{ id: '11-08', text: 'duplicate' }, { id: '11-09', text: 'invalid' },
{ id: '11-10', text: 'wontfix' }];
function matchCustom(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// Do not display the item if there is no 'text' property
if (typeof data.text === 'undefined') {
return null;
}
// search by value
if (data.text.indexOf(params.term) > -1) {
return data;
}
// search by id
if (data.id.indexOf(params.term) > -1) {
return data;
}
// Return `null` if the term should not be displayed
return null;
}
$(".js-example-data-array").select2({
data: data,
matcher: matchCustom
});
});
.js-example-data-array {
width: 200px;
}
<select class="js-example-data-array"></select>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/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/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>

SELECT2 AJAX not selecting results - Ember.js Ember Cli Custom Component

The AJAX functionality of Select2 4.0.0 doesn't seem to be working. It displays the results from the AJAX however when you click on the a result item it does not select it. I have wasted hours on this any help would be appreciated.
The following code does not work:
var staticdata = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
self._select = self.$().select2({
placeholder: self.get('placeholder'),
tokenSeparators: [','],
multiple: true,
ajax: {
url: "http://localhost:9990/api/v1/users/",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: staticdata
};
},
cache: true
}
});
However when I try it WITHOUT Ajax it works and the results are selecting into the input field:
var staticdata = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
self._select = self.$().select2({
placeholder: self.get('placeholder'),
tokenSeparators: [','],
multiple: true,
data: staticdata
});
So this issue was due to using select2 as custom ember component.
When you create an ember component you can either select an existing html tag e.g.
1. self.$('#selecttext').select2(...)
Where the html tag is located in your ember cli location templates/components/select2-component.hbs:
<select id="selecttext" class=" form-control input-md select2-hidden-accessible" multiple="" tabindex="-1" aria-hidden="true">
</select>
OR alternatively just initialize the component it self using:
2. self.$().select2(...)
When using approach 2. I am guessing select2 AJAX callback somehow loses the reference to select2 component. So that when you select a result from the list select2:selecting event is not generated and hence the result value is not selected.
I tested this using:
self._select.on("select2:selecting", function(e) {
alert('selecting');
});
However when you use approach 1. ajax callback does NOT lose the reference to the select2 component and generates the "select2:selecting" event and works as expected with the results being able to be selected.
Hence this works:
didInsertElement: function() {
var self = this;
var staticdata = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
self._select = self.$('#selecttext').select2({
// note we are explicitly initialising select2 component on #selecttext
placeholder: self.get('placeholder'),
tokenSeparators: [','],
multiple: true,
tags: false,
//data: staticdata
ajax: {
url: "http://localhost:9990/api/v1/users/",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data, page) {
return {
results: staticdata
};
},
cache: true
}
}); //select2 END
} //didInsertElement END

Filter dropdown goes beyond the filter popup in jqxgrid

I am using jqxgrid widget, which is a jquery grid widget.
I am finding that the filter conditions dropdown is extending beyond the filter popup and this is causing the filter popup to automatically close if I click the last item in the filter conditions dropdown. So its impossible to filter when using the last item in conditions dropdown. You can see this in screen shot attached. I cannot filter on null or not null conditions due to this.
How can I prevent this?
Code for jqxGrid is as below.
$("#jqxgrid").jqxGrid({
theme: 'ui-start',
width: 740,
source: dataAdapter,
pageable: true,
sortable: true,
filterable: true,
autoheight: true,
virtualmode: true,
rendergridrows: function (args) {
return args.data;
},
updatefilterconditions: function (type, defaultconditions) {
var stringcomparisonoperators = ['EMPTY', 'NOT_EMPTY', 'CONTAINS',
'DOES_NOT_CONTAIN', 'STARTS_WITH',
'ENDS_WITH', 'EQUAL', 'NULL', 'NOT_NULL'];
var numericcomparisonoperators = ['EQUAL', 'NOT_EQUAL', 'LESS_THAN', 'LESS_THAN_OR_EQUAL', 'GREATER_THAN', 'GREATER_THAN_OR_EQUAL', 'NULL', 'NOT_NULL'];
var datecomparisonoperators = ['EQUAL', 'NOT_EQUAL', 'LESS_THAN', 'LESS_THAN_OR_EQUAL', 'GREATER_THAN', 'GREATER_THAN_OR_EQUAL', 'NULL', 'NOT_NULL'];
var booleancomparisonoperators = ['EQUAL', 'NOT_EQUAL'];
switch (type) {
case 'stringfilter':
return stringcomparisonoperators;
case 'numericfilter':
return numericcomparisonoperators;
case 'datefilter':
return datecomparisonoperators;
case 'booleanfilter':
return booleancomparisonoperators;
}
},
updatefilterpanel: function (filtertypedropdown1, filtertypedropdown2, filteroperatordropdown, filterinputfield1, filterinputfield2, filterbutton, clearbutton,
columnfilter, filtertype, filterconditions) {
var index1 = 0;
var index2 = 0;
if (columnfilter != null) {
var filter1 = columnfilter.getfilterat(0);
var filter2 = columnfilter.getfilterat(1);
if (filter1) {
index1 = filterconditions.indexOf(filter1.comparisonoperator);
var value1 = filter1.filtervalue;
filterinputfield1.val(value1);
}
if (filter2) {
index2 = filterconditions.indexOf(filter2.comparisonoperator);
var value2 = filter2.filtervalue;
filterinputfield2.val(value2);
}
}
filtertypedropdown1.jqxDropDownList({ autoDropDownHeight: true, selectedIndex: index1 });
filtertypedropdown2.jqxDropDownList({ autoDropDownHeight: true, selectedIndex: index2 });
},
columns: [
{ text: 'Sales Order ID', dataField: 'SalesOrderID', width: 120 },
{ text: 'Sales Order Number', dataField: 'SalesOrderNumber', width: 120 },
{ text: 'Purchase Order Number', dataField: 'PurchaseOrderNumber', width: 120 },
{ text: 'Customer ID', dataField: 'CustomerID', width: 120 },
{ text: 'Order Date', dataField: 'OrderDate', width: 130, cellsformat: 'MM-dd-yyyy' },
{ text: 'Due Date', dataField: 'DueDate', width: 130, cellsformat: 'MM-dd-yyyy' }
]
});
It seems that writing down your question in detail can sometimes suddenly provide you with the solution and answer. In my case, it did.
I have set autoDropDownHeight to true in my code, which actually needs to be set to false.
The correct code should have been as below.
filtertypedropdown1.jqxDropDownList({ autoDropDownHeight: false, selectedIndex: index1 });
filtertypedropdown2.jqxDropDownList({ autoDropDownHeight: false, selectedIndex: index2 });

Resources