does autocomplete works on multiple files - javascript

I am using EasyAautocomplete on my project. I was wondering if its possible to use autocomplete from 2 different file in one single searchbox. I have tried beyond the code but it reads only one of them:
<script>
var options = {
url: "file1.json",
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options);$('div.easy-autocomplete').removeAttr('style');
var options2 = {
url: "file2.json",
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options2);$('div.easy-autocomplete').removeAttr('style');
</script>

I recommend to you that:
Get json files at first
Merge them
Use them for autocomplete
The code is like:
$.getJSON("file1.json", function (data1) {
$.getJSON("file2.json", function (data2) {
var mergedData = $.extend({}, data1, data2);
var options = {
data: mergedData,
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});

Related

disallow blank/empty cells in kendo grid

How could I disallow a cell in my kendo grid to be 'blank' or 'empty' rather... How could I replace all blank or empties with a 0..
I have a save button grabbing the values from my kendo grid such as below: Everything works fine EXCEPT, it is completely omitting my empty cells.. I want to keep them, just have a 0 value on them...
Save button: want to keep the empties with simply a 0 or N/A..
$('.' + chs).on('click', '#saveChanges', function(e) {
which = $(frm).attr("class");
let dataSource = $("#grid").data("kendoGrid").dataSource,
data = dataSource.data(),
changedModels = [];
if(dataSource.hasChanges) { // only saves cells/row that have been edited/changed, need to keep this
for(var i = 0; i < data.length; i++) {
if(data[i].dirty) { changedModels.push(data[i].toJSON()) }
}
}
let ds = JSON.stringify(changedModels);
$.ajax({
type: "POST",
url: "saveGrid",
dataType: "json",
data: {
id: which,
data: ds
},
success: function(result) {
console.log('yy');
},
error: function(result) {
console.log('nn');
}
});
});
This is my kendo grid initialized:
let dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/popGrid?id=" + which,
dataType: "json"
},
},
batch: true,
schema: {
data: "data",
model: {
id: id,
}
},
});
console.log(id);
$("#grid").kendoGrid({
dataSource: dataSource,
height: 600,
sortable: true,
autoBind: true,
nullable: true,
editable: {
createAt: "top"
},
change: function(e) {
let grid = $("#grid").data("kendoGrid");
let selectedItem = grid.dataItem(grid.select());
let val = selectedItem.id;
console.log(val);
},
selectable: "row",
toolbar: [
{ name: "create" },
{ name: "cancel" }
],
paging: false,
});
I can't understand if you want to POST empty fields as "0" or if you want to SHOW them in the grid as "0", when null or "empty".
But I guess you're talking about posting it as "0". In that case I think you have to do that before posting:
let fieldName = 'myCell';
if (data[i].dirty) {
if (!data[i].hasOwnProperty(fieldName) || // In case field is not present on data
!data[i][fieldName]) { // In case field value is null/undefined/0/false/empty string
data[i][fieldName] = 0;
}
changedModels.push(data[i].toJSON());
}
For multiple field check:
let fieldNames = ['fieldA', 'fieldB', ...],
checkFields = (item) => {
fieldNames.forEach(field => {
if (!item.hasOwnProperty(field) || // In case field is not present on data
!item[field]) { // In case field value is null/undefined/0/false/empty string
item[field] = 0;
}
});
};
Or you can do the same before data is bound to the grid with dataSource.schema.parse.

Why ui-grid reset to default state, after set filter, after restore state?

I'll created ui-grid and make functionality to save grid state to cookies via localStorageService. Then I change column width and save this state. After I restore state via 'gridApi.saveState.restore' and this do is perfect, but when I set filter, grid reset column to default width.
Please tell Me if I do something wrong.
$scope.enableFiltering = function () {
var isEnabledFiltering = localStorageService.get('enableFiltering');
if (!_.isNull(isEnabledFiltering) && !_.isUndefined(isEnabledFiltering)) {
return JSON.parse(isEnabledFiltering);
}
return false;
};
$scope.colDefs = [
{
displayName: locMsg['id'],
field: 'id',
enableHiding: true,
visible: false,
headerCellClass: 'header-filtered',
filters: [{
condition: uiGridConstants.filter.CONTAINS
}]
},
{
displayName: locMsg['name'],
field: 'name',
enableHiding: true,
headerCellClass: 'header-filtered',
filters: [{
condition: uiGridConstants.filter.CONTAINS
}],
},];
$scope.regularGridStateName = "grid";
$scope.defaultGridStateName = "defaultGrid";
$scope.gridOptions = {
enableFiltering: $scope.enableFiltering(),
enableGridMenu: true,
columnDefs : $scope.colDefs
};
$scope.toggleFiltering = function () {
$scope.gridOptions.enableFiltering = !$scope.gridOptions.enableFiltering;
localStorageService.set('enableFiltering', $scope.gridOptions.enableFiltering);
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
var gridState = localStorageService.get($scope.regularGridStateName);
if (gridState) {
gridApi.saveState.restore($scope, gridState);
}
};
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
$scope.gridOptions.gridMenuCustomItems.push({
title: 'Reset table',
action: function () {
var defaultState = localStorageService.get($scope.defaultGridStateName);
localStorageService.set($scope.regularGridStateName, defaultState);
if (defaultState) {
gridApi.saveState.restore($scope, defaultState);
}
},
order: 220
});
$scope.gridOptions.gridMenuCustomItems.push({
title: 'Save table state',
action: function () {
localStorageService.set($scope.regularGridStateName, $scope.gridApi.saveState.save());
},
order: 221
});
$timeout(function () {
gridStateService.saveDefaultStateIfNotExist($scope.defaultGridStateName, $scope.gridApi.saveState.save());
var defaultState = localStorageService.get($scope.defaultGridStateName);
if (!defaultState) {
localStorageService.set($scope.regularGridStateName, $scope.gridApi.saveState.save());
}
var gridState = localStorageService.get($scope.regularGridStateName);
if (gridState) {
gridApi.saveState.restore($scope, gridState);
}
}, 10);
This problem has been solved, just need to update to new version.
I had similar issue and this is due to the caching of column order. Try the following
gridApi.saveState.restore(this.scope, this.scope.tableState);
var columnDefsColMov = gridApi.grid.moveColumns.orderCache;
columnDefsColMov.length = 0;
columnDefsColMov.push.apply(columnDefsColMov, gridApi.grid.columns.slice());
gridApi.core.notifyDataChange(this.uiGridConstants.dataChange.COLUMN);

ExtJS TaskRunner

I'm still in the learning process with EXTJS and any help would be much appreciated.
The goal for me is to load data into a grid where one cell needs to have the value incremented every minute. From my research using the TaskRunner function is the way to go but can't figure out where to put it and how to use it. My assumption is that it needs to go into the model or the controller but I'm not sure. In my simple project I'm using the MVC architecture.
Currently my gird works as expected. It reads in a file does a date conversion that produces a minute value. It's that minute value that I need to increment.
The code below is a sample TaskRunner snippit that I'm working with, right or wrong I don't know yet.
var runner = new Ext.util.TaskRunner();
var task = runner.newTask({
run: store.each(function (item)
{
var incReq = item.get('request') + 1;
item.set('request', incReq);
}),
interval: 60000 // 1-minute interval
});
task.start();
Model:
Ext.define("myApp.model.ActionItem", {
extend : "Ext.data.Model",
fields : [
{
name: 'pri',
type: 'int'
},
{
name: 'request',
type: 'int',
defaultValue: 0,
convert : function(v, model) {
return Math.round((new Date() - new Date(v)) / 60000);
}
}
]
});
Controller:
Ext.define("myApp.controller.HomeController", {
extend: "Ext.app.Controller",
id: "HomeController",
refs: [
{ ref: "ActionItemsGrid", selector: "[xtype=actionitemgrid]" },
{ ref: "DetailsPanel", selector: "[xtype=actionitemdetails]" }
],
pri: "",
models: ["ActionItem"],
stores: ["myActionStore"],
views:
[
"home.ActionItemDetailsPanel",
"home.ActionItemGrid",
"home.HomeScreen"
],
init: function () {
this.control({
"#homescreen": {
beforerender: this.loadActionItems
},
"ActionItemsGrid": {
itemclick: this.displayDetails
}
});
},
displayDetails: function (model, record) {
this.getDetailsPanel().loadRecord(record);
},
loadActionItems: function () {
var store = Ext.getStore("myActionStore");
store.load();
this.getActionItemsGrid().reconfigure(store);
}
});
View:
Ext.define("myApp.view.home.ActionItemGrid", {
extend: "Ext.grid.Panel",
xtype: "actionitemgrid",
resizable: true,
multiSelect: false,
enableDragDrop : false,
store: null,
columns:
[
{ header: "Pri", dataIndex: "pri", sortable: false, autoSizeColumn: true},
{ header: "Req", dataIndex: "request", sortable: false, autoSizeColumn: true}
],
viewConfig:
{
listeners: {
refresh: function(dataview) {
Ext.each(dataview.panel.columns, function(column) {
if (column.autoSizeColumn === true)
column.autoSize();
})
}
}
}
});
Sample JSON File:
{
"actionitems" : [
{
"pri": 1,
"request": "2014-12-30T03:52:48.516Z"
},
{
"pri": 2,
"request": "2014-12-29T05:02:48.516Z"
}
]
}
You have error in code which creates task - you should provide function to run configuration property, not result of invocation. Try this:
var runner = new Ext.util.TaskRunner();
var task = runner.newTask({
run: function() {
store.each(function (item)
{
var incReq = item.get('request') + 1;
item.set('request', incReq);
})
},
interval: 60000 // 1-minute interval
});
task.start();
You can put that code in loadActionItems method.

javascript function not call in document.ready

I have two functions that make two combobox with jqwidgets libraries. two functions are mostly like each other. I call them in $(document).ready(function (), but first function is work well and the second not even call. I put the codes those in one function, but the second part never run.
function f1() {
var url2 = "/autosuggest/JsonOrigins.aspx";
var source2 = {
datatype: "json",
datafields: [{
name: 'id'
}, {
name: 'name'
}],
url: url2,
async: false
};
var dataAdapter2 = new $.jqx.dataAdapter(source2);
// Create a jqxComboBox
$("#originsjqxWidget").jqxComboBox({
source: dataAdapter2,
multiSelect: true,
displayMember: "name",
valueMember: "id",
width: 145
});
$("#arrow").jqxButton({});
$("#arrow").click(function () {
$("#originsjqxWidget").jqxComboBox({
showArrow: false
});
});
$("#originsjqxWidget").on('change', function (event) {
var items = $("#originsjqxWidget").jqxComboBox('getSelectedItems');
var selectedItems = "Selected Items: ";
$.each(items, function (index) {
selectedItems += this.label;
if (items.length - 1 != index) {
selectedItems += ", ";
}
});
$("#log").text(selectedItems);
});
};
function f2() {
var url = "/autosuggest/JsonTag.aspx";
var source = {
datatype: "json",
datafields: [{
name: 'id'
}, {
name: 'name'
}],
url: url,
async: false
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#categoriesjqxWidget").jqxComboBox({
source: dataAdapter,
multiSelect: true,
displayMember: "name",
valueMember: "id",
width: 145
});
$("#arrow").jqxButton({});
$("#arrow").click(function () {
$("#jqxComboBox").jqxComboBox({
showArrow: false
});
});
$("#categoriesjqxWidget").on('change', function (event) {
var items = $("#categoriesjqxWidget").jqxComboBox('getSelectedItems');
var selectedItems = "Selected Items: ";
$.each(items, function (index) {
selectedItems += this.label;
if (items.length - 1 != index) {
selectedItems += ", ";
}
});
$("#log").text(selectedItems);
});
}
$(document).ready(function () {
f1();
f2();
});
Remove the ; after your first function.
try this
var source2 = {
datatype: "json";
datafields: [{
name: 'id'
}, {
name: 'name'
}],
url: url2,
async: false
};
I think you have an extra ; at the end of function f1
function f1(){
...
if (items.length - 1 != index) {
selectedItems += ", ";
}
});
$("#log").text(selectedItems);
});
};

Select2: how to set data after init?

I need to set an array of data after initializing select2. So I want to make something like this:
var select = $('#select').select2({});
select.data([
{id: 1, text: 'value1'},
{id: 1, text: 'value1'}
]);
But I get the following error:
Option 'data' is not allowed for Select2 when attached to a element.;
My HTML:
<select id="select" class="chzn-select"></select>
What should I use instead of a select element?
I need to set the source of items for search
In onload:
$.each(data, function(index, value) {
$('#selectId').append(
'<option value="' + data[index].id + '">' + data[index].value1 + '</option>'
);
});
Make an <input type="hidden"> element and bind select2 to that. Using .select2 on a regular select box doesn't let you play with the data, it just mostly gives you the UI and post-selection methods.
Source:
Select2 Documentation
Source: https://select2.org/programmatic-control/add-select-clear-items
Add item:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
Clear items:
$('#mySelect2').val(null).trigger('change');
For v4 you'll have to destroy and reconstruct select2 with updated data. Check https://github.com/select2/select2/issues/2830
I've recently had the scenario where changing one select2 object alters the contents of a second (parent - child groupings effectively). I used an ajax call to retrieve a new set of Json data, which was then picked up by the second select2 object. I've included the code below:
$("#group").on('change', function () {
var uri = "/Url/RetrieveNewResults";
$.ajax({
url: uri,
data: {
format: 'json',
Id: $("#group :selected").val()
},
type: "POST",
success: function (data) {
$("#groupchild").html('');
$("#groupchild").select2({
data: data,
theme: 'bootstrap',
placeholder: "Select a Type"
});
},
error: function () {
console.log("Error")
}
});
});
I found that I had to include the $("#groupchild").html('') in order to clear out the previous set of data in the second select2. Hope this helps.
You can rerender and trigger the select2
render select2
$('.select2').select2({
placeholder: 'Slect value',
allowClear: true
});
after need to change the data data
let dataChange = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 2,
text: 'duplicate'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
rerender the select2
$('.select2').select2('destroy');
$('.select2').empty();
$('.select2').select2({
placeholder: 'Slect value',
allowClear: true,
data: dataChange
});
trigger select2
$('.select2').trigger('change');
Hope this is the answer for you :3
Here's what I did.
1. Extend select2
Select2.prototype.setAjax = function (ajaxOptions)
{
// Set the new ajax properties
var oAjaxOpts = this.options.get('ajax');
if (oAjaxOpts != undefined && oAjaxOpts != null)
{
for (var sKey in ajaxOptions)
{
oAjaxOpts[sKey] = ajaxOptions[sKey];
}
}
var DataAdapter = this.options.get('dataAdapter');
this.dataAdapter = new DataAdapter(this.$element, this.options);
}
2. Initialize as usual (for example --- yours could be different)
jHtmlFrag.select2({
dropdownParent: $(oData.jDiv),
placeholder: "Select Option",
allowClear: true,
minimumInputLength: 2,
ajax: {
url: "",
method: "POST",
dataType: 'json',
delay: 250,
processResults: function (oResults, params)
{
let page = params.page || 1;
// console.log(oResults, (params.page * 10));
return {
results: oResults.data,
pagination: {
more: (page * 10) < oResults.recordsFiltered
}
};
}
}
}).val(null).trigger('change');
3. Set Ajax options dynamically when you feel like by calling the new extension func
jCombo.select2('setAjax', {
url: sUrl,
data: function (params)
{
let query = {
search: params.term,
type: params._type,
page: params.page || 1,
}
return query;
},
});

Categories

Resources