Select2 and Jexcel add new option to dropdown - javascript

I have this code of Jexel with Select2 where I load the default values for each jexcel row from an array and use select2 for the dropdown:
https://jsfiddle.net/ktumw528/
However I wish to know how can I populate the options from select2 with the values from var data?
Also how can I add new country to the select2 dropdown if not found when typing.
var data = [
['Spain'],
['France'],
['Germany'],
];
var customDropDown1 = {
// Methods
closeEditor : function(cell, save) {
// Get value
var txt = $(cell).find('.editor').val();
// Set visual value
$(cell).html(txt);
// Close edition
$(cell).removeClass('edition');
// Save history
return txt;
},
openEditor : function(cell) {
// Get current content
var currentValue = $(cell).text();
// Create the editor
var editor = document.createElement('select');
$(cell).html(editor);
$(editor).prop('class', 'editor');
$(editor).html('<option>Brazil</option><option>Canada</option>')
$(editor).val(currentValue);
// Create the instance of the plugin
$(editor).select2().on('select2-blur', function() {
$('#' + $.fn.jexcel.current).jexcel('closeEditor', $(cell), true);
});
},
getValue : function(cell) {
return $(cell).text();
},
setValue : function(cell, value) {
$(cell).html(value);
return true;
}
}
$('#my').jexcel({
data:data,
columns: [ { editor:customDropDown1 } ],
colHeaders: ['Country'],
colWidths: [ 300 ]
});
Any tips are welcomed :) thanks a lot!

I think you can use last version of JExcel (v4). You will have more options and more option editor.
With this new version, you can create editor with set custom value. And you have an option for dropdown for add new item
https://bossanova.uk/jexcel/v4/examples/dropdown-and-autocomplete
and this documentation : https://bossanova.uk/jsuites/dropdown-and-autocomplete/new-options
Example :
<script>
var data5 = [
[1, 'Beatles'],
[2, 'Beatles'],
[3, 'Beatles'],
[4, 'Beatles'],
];
jexcel(document.getElementById('spreadsheet5'), {
data: data5,
columns: [
{
type: 'dropdown',
title: 'Name',
width: '300px',
source: [
{ id:'1', name:'Paul' },
{ id:'2', name:'Ringo' },
{ id:'3', name:'George' },
{ id:'4', name:'John' },
],
options: { newOptions: true } // Option for add new options
},
{
type:'dropdown',
title:'Band',
width:'200px',
source: ['Beatles'],
},
],
});
<script>
otherwise if you want keep v2, i suggest use external source on var, and add new item on this variable. Because the editor is created only on open cell.

Related

Tabulator: how to modify local array when deleting rows?

I'm trying to build an interactive table that could be modified by the user. In my case, the original dataset is a local array of objects.
Tabulator has the buttonCross option to delete rows, but it only affects the table visuals. How can I make it find the matching object the row presents and delete it from the tabledata array?
Here's the code I'm working with:
let tabledata = [{
animal: "hippo",
color: "grey"
},
{
animal: "puma",
color: "black"
},
{
animal: "flamingo",
color: "pink"
}
];
let table = new Tabulator("#example-table", {
data: tabledata,
layout: "fitDataFill",
addRowPos: "bottom",
reactiveData: true,
headerSort: false,
columns: [ //define the table columns
{
title: "animal",
field: "animal",
editor: "input"
},
{
title: "color",
field: "color",
editor: "input"
},
{
formatter: "buttonCross",
width: 40,
align: "center",
cellClick: function (e, cell) {
cell.getRow().delete();
}
},
],
});
Codepen here.
Would really appreciate some tips on how to make this work!
Working example for tabulator
the filter function is used to remove the current item for the collection
filter Filter API.
First filter the object you don't need and then assign it to tabledata.
cellClick: function (e, cell) {
debugger;
var animalToDelete={ animal:cell.getRow().getData().animal,
color:cell.getRow().getData().color
};
var filtered=tabledata.filter(function(x){
debugger;
return x.animal!=animalToDelete.animal
&& x.color!=animalToDelete.color;
});
tabledata=filtered;
cell.getRow().delete();
}
You could also look to use tabulator in Reactive Data Mode
In this mode it will update the table in real time to match the provided data array as it is changed, and vice versa it will update the array to match the table.
To do this set the reactiveData property to true in the tables constructor object.
//create table and assign data
var table = new Tabulator("#example-table", {
reactiveData:true, //enable reactive data
data:tableData, //assign data array
columns:[
{title:"Name", field:"name"},
{title:"Age", field:"age", align:"left", formatter:"progress"},
{title:"Favourite Color", field:"col"},
{title:"Date Of Birth", field:"dob", sorter:"date", align:"center"},
]
});
It will then maintain a link with the initial data source

Adding a custom drop down tool to the Quill Editor with JavaScript

Please note this is a self-answered question.
The Quill Editor's toolbar module doesn't appear to offer a way to add custom tools to it using the JavaScript API. You can merely choose from a list of predefined tools or you have to completely rewrite the entire HTML of the toolbar which seems very hacky and often is not an option. Because of that mechanism, tools can't just be added or removed during runtime and are always static, meaning that (for example) you can't have a dynamic drop down list that loads or changes it's entries during runtime.
The Quill Editor itself only offers an API to add another module. So you could write another toolbar module that supports the above mentioned features the original one is lacking, but it would be much nicer to be able to continue using the original one because of the amount of work that would be required to effectively rewrite it.
The question is: How to add a potentially dynamic tool like a drop down menu to an existing Quill Editor instance's toolbar.
I wrote a library called DynamicQuillTools which can do the job.
It can be used like this:
const dropDownItems = {
'Mike Smith': 'mike.smith#gmail.com',
'Jonathan Dyke': 'jonathan.dyke#yahoo.com',
'Max Anderson': 'max.anderson#gmail.com'
}
const myDropDown = new QuillToolbarDropDown({
label: "Email Addresses",
rememberSelection: false
})
myDropDown.setItems(dropDownItems)
myDropDown.onSelect = function(label, value, quill) {
// Do whatever you want with the new dropdown selection here
// For example, insert the value of the dropdown selection:
const { index, length } = quill.selection.savedRange
quill.deleteText(index, length)
quill.insertText(index, value)
quill.setSelection(index + value.length)
}
myDropDown.attach(quill)
Here is a full demo adding a custom drop down tool and a custom button to a Quill Editor instance:
// Create a Quill Editor instance with some built-in toolbar tools
const quill = new Quill('#editor', {
theme: 'snow',
modules: {
toolbar: {
container: [
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }],
[{ 'indent': '-1' }, { 'indent': '+1' }],
[{ 'direction': 'rtl' }],
[{ 'size': ['small', false, 'large', 'huge'] }],
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }],
[{ 'font': [] }],
[{ 'align': [] }],
['clean'],
]
}
}
})
// Add a custom DropDown Menu to the Quill Editor's toolbar:
const dropDownItems = {
'Mike Smith': 'mike.smith#gmail.com',
'Jonathan Dyke': 'jonathan.dyke#yahoo.com',
'Max Anderson': 'max.anderson#gmail.com'
}
const myDropDown = new QuillToolbarDropDown({
label: "Email Addresses",
rememberSelection: false
})
myDropDown.setItems(dropDownItems)
myDropDown.onSelect = function(label, value, quill) {
// Do whatever you want with the new dropdown selection here
// For example, insert the value of the dropdown selection:
const { index, length } = quill.selection.savedRange
quill.deleteText(index, length)
quill.insertText(index, value)
quill.setSelection(index + value.length)
}
myDropDown.attach(quill)
// Add a custom Button to the Quill Editor's toolbar:
const myButton = new QuillToolbarButton({
icon: `<svg viewBox="0 0 18 18"> <path class="ql-stroke" d="M5,3V9a4.012,4.012,0,0,0,4,4H9a4.012,4.012,0,0,0,4-4V3"></path></svg>`
})
myButton.onClick = function(quill) {
// Do whatever you want here. You could use this.getValue() or this.setValue() if you wanted.
// For example, get the selected text and convert it to uppercase:
const { index, length } = quill.selection.savedRange
const selectedText = quill.getText(index, length)
const newText = selectedText.toUpperCase()
quill.deleteText(index, length)
quill.insertText(index, newText)
quill.setSelection(index, newText.length)
}
myButton.attach(quill)
<script src="https://cdn.quilljs.com/1.3.7/quill.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.quilljs.com/1.3.7/quill.bubble.css"></link>
<link rel="stylesheet" type="text/css" href="https://cdn.quilljs.com/1.3.7/quill.snow.css"></link>
<script src="https://cdn.jsdelivr.net/gh/T-vK/DynamicQuillTools#master/DynamicQuillTools.js"></script>
<div id="editor">The last two elements in the toolbar are our custom tools. The first one (<b>Email Addresses</b>) is a simple drop down menu that inserts the email address of the person selected and the second one (<b>U</b>) is a simple button that makes the selected text uppercase.</div>
I know this is old but I just came across this on accident (https://quilljs.com/docs/modules/toolbar/). The solution is to add the class "ql-size" to the select as shown in the container section.

Apply background-color to dxDataGrid control and export to Excel

I'm using DevExpress's dxDataGrid in a ASP.NET project for show some data stored on a SQL Server database.
The following code shows how I'm setting the dxDataGrid control for render the data:
// Variables.
var vlrMin = [];
var vlrMax = [];
var vlr_to_match = 0;
var colors = [];
var final_rst = "";
// Add values to variables:
vlrMin.push("9");
vlrMin.push("2");
vlrMin.push("9");
// Add values to variables:
vlrMax.push("13");
vlrMax.push("7");
vlrMax.push("4");
colors.push('#ff0000');
colors.push('#92D050');
colors.push('#5B9BD5');
// Start configuration.
$("#gridContainer").dxDataGrid({
dataSource: [{
"Dept": "Local services",
"Employee": "John Doe",
"TotalHours": "11"
}],
paging: {
pageSize: 10
},
export: {
allowExportSelectedData: true,
enabled: true,
fileName: 'Reporte 1',
texts: {
exportAll: 'Export all',
exportSelectedRows: 'Export selected row(s).',
exportTo: 'Export'
},
},
searchPanel: {
visible: true
},
filterRow: {
visible: true,
showOperationChooser: true
},
allowColumnReordering: true,
grouping: {
autoExpandAll: true
},
groupPanel: {
visible: true
},
pager: {
showPageSizeSelector: true,
allowedPageSizes: [5, 10, 20],
showInfo: true
},
columns: ['Dept',
'Employee', {
dataField: 'TotalHours',
allowFiltering: true,
allowSorting: true,
cellTemplate: function(container, options) {
/* Value to check if matches with the criteria. */
var vlr_to_match = options.value;
/* Loop elements. */
for (var mn = 0; mn < vlrMin.length; mn++) {
if (vlr_to_match >= vlrMin[mn] && vlr_to_match <= vlrMax[mn]) {
final_rst = colors[mn];
break;
}
}
/* Apply custom style to element. */
$('<span>').text(options.data.TotalHours)
.attr('style', 'background-color: ' + final_rst)
.appendTo(container);
}
}
]
});
This is the results in the dxDataGrid control:
But, when I open the generated file "using the DevExpress functionality" I'm not getting the same results as is shown in the screenshot (i.e; the cell has values, but no styles are applied).
According to the documentation, and after apply a color to an specific cell in the dxDataGrid control, when the exported Excel file is opened, the cell is not getting the same result as is shown in the dxDataGrid control.
My question is:
How can apply styles to a dxDataGrid cell and apply such results to the generated Excel file?
unfortunately, based on the quite recent (2016-09-20) reply from DX stuff in their support forum, there is no way in DevExtreme suit to export dxDataGrid to excel with formatting.
See yourself: https://www.devexpress.com/Support/Center/Question/Details/T429240
If you were using the DevEpress ASPxGridView control together with ASPxGridViewExporter you would be able to customize format in the exported Excel doc per cell or per row.

How can i access to object elements in javascript?

I'am using the jQuery Gantt api, and I want to access to certain elements, but I don't know how.
$(function() {
"use strict";
//var obj = JSON.parse($(".gantt").gantt);
$(".gantt").gantt({
source: [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
}],
navigate: "scroll",
scale: "weeks",
maxScale: "months",
minScale: "days",
itemsPerPage: 10,
onItemClick: function(data) {
alert("Item clicked - show some details");
},
onAddClick: function(dt, rowId) {
alert("Empty space clicked - add an item!");
},
onRender: function() {
if (window.console && typeof console.log === "function") {
console.log("chart rendered");
}
}
});
//alert("OK");
//var parsedData = JSON.parse();
//alert($(".gantt").gantt.source);
$(".gantt").popover({
selector: ".bar",
title: "I'm a popover",
content: "And I'm the content of said popover.",
trigger: "hover"
});
prettyPrint();
});
I found this ape with static example, but am trying to draw my own chart by changing content of element source.
so can some tell me how can i get the element source from the gantt object.
Do you expecting this?
To access gantt elements through object try like this.
var ganttObj = $(".gantt").data("gantt");
Or try to create instance for your gantt like this.
var ganttObj = $(".gantt").gantt("instance");
ganttObj.model.maxScale = "years" //To change `maxScale` property values dynamically
Or you can also directly access your elements like this.
For eg: To change maxScale value from months to years, you can use like below.
$(".gantt").gantt({ maxScale: "years" });
Please let me know if this helps you.
Based on your example, you could simply move the source data into a variable so you can reference it later:
var ganttSource = [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
}];
$(".gantt").gantt({
source: ganttSource,
...
});
console.log(ganttSource);

Updating Columns Dynamically - Alloy UI

I'm trying to change columns dynamically in my Alloy UI DataTable - depending on what button is selected, columns are changed depending on which data is returned.
My columns get updated, however the actual data is never included in the table. When I don't define any columns both the columns and data are returned - I of course want control of how my columns are displayed and want to set their attributes
Below is my code:
var dataTable = new Y.DataTable({ //Defining Datatable with no columns preset
editEvent: 'dblclick',
plugins: [{
cfg: {
highlightRange: false
}]
});
button.on(
'click', //On Click...
function() {
var category = $(this).attr("id"); //value retrieved from id of button selected
dataSource = new Y.DataSource.IO({source: '/searchMyData
dataSource.sendRequest({
dataType: 'json',
on: {
success: function(e) {
response = e.data.responseText;
setColumnNames(category); //Set the Columns...
data = Y.JSON.parse(response);
dataTable.set('data', data);//Then the Data
dataTable.render('#my-container');
},
failure: function() {
alert(e.error.message);
}
}
});
function setColumnNames(tabName){ //Defining Columns
var columns1 = [
{ key: 'id', label: 'ID', width: '70px' },
{ key: 'name', label: 'Name', width: '70px' }
];
var columns2 = [
{ key: 'id', label: 'ID', width: '70px' },
{ key: 'addr', label: 'Address', width: '70px' }
];
switch (category) {
case "person":
dataTable.set('columns', columns1);
break;
case "address":
dataTable.set('columns', columns2);
break;
default:
console.log('');
}
There's no issue with the data returning from the ajax request, only when it comes to loading it to the table with a new set of columns defined. I've tried the reset() method on both columns and data on each click, but no luck.
It turns out the keys returned from my request were being capitalized and included underscores (just how they're defined in the database) - I've also noticed defining the columns key is case sensitive. If I changed a single character from lower case to upper than the column would not display data.

Categories

Resources