Im am developing a placeholder plugin to CKEDITOR and it´s basically complete. The problem I have is that I am trying to get the value and description from the select within the dialog and I am only getting the value.
The array that contains the description and value looks like this
-->
items: [['description1', 'value1'], ['description2', 'value2']] <--
In the return -> contents -> elements with ID dropdown I have setup and commit function. In these functions I need to get the description just like getting the name from select option.
Really need help with this one, thanks in advance
example -->
<select>
<option value="value1">description1</option>
<option value="value2">description2</option>
</select>
example <--
(function () {
function placeholderDialog(editor, isEdit) {
var lang = editor.lang.phlink,
generalLabel = editor.lang.common.generalTab;
return {
title: lang.title,
minWidth: 300,
minHeight: 80,
contents: [
{
id: 'info',
label: generalLabel,
title: generalLabel,
elements: [
{
id: 'dropdown'
, type: 'select'
, label: lang.chooseVal
, 'default': 'Detta är default'
, items: [['description1', 'value1'], ['description2', 'value2']]
, setup: function (data) {
// need the description
this.setValue(data.title);
}
, commit: function (data) {
// need the description
data.title = this.getValue();
}
},
{
id: 'text',
type: 'text',
style: 'width: 100%;',
label: lang.text,
'default': '',
required: true,
validate: CKEDITOR.dialog.validate.notEmpty(lang.textMissing),
setup: function (data) {
this.setValue(data.text);
},
commit: function (data) {
data.text = this.getValue();
}
}
]
}
],
onShow: function () {
var data = { tag: 'link', content: "detta är innehåll", title: "Länk till svar", text: "detta är text" };
if (isEdit) {
this._element = CKEDITOR.plugins.phlink.getSelectedPlaceHolder(editor);
data.title = this._element.getAttribute('title');
data.text = this._element.getText();
data.tag = this._element.getAttribute('data-jztag');
}
this.setupContent(data);
},
onOk: function () {
var data = { tag: 'link', content: null, title: null, text: null };
this.commitContent(data);
CKEDITOR.plugins.phlink.createPlaceholder(editor, this._element, data);
delete this._element;
}
};
}
CKEDITOR.dialog.add('createplaceholder', function (editor) {
return placeholderDialog(editor);
});
CKEDITOR.dialog.add('editplaceholder', function (editor) {
return placeholderDialog(editor, 1);
});
})();
Use the following to get option's text:
var input = this.getInputElement().$;
console.log( input.options[ input.selectedIndex ].text );
>> "description1"
Related
How can I get the first element of an array in javascript by a means other than array[0]?
I do not know why, but for some reason the array that gets passed into the method has its first, and only, element at index 5, not 0.
Edit - Here is my attempt at providing a minimal reproducible example.
// Initialize database connection string datatable editor
editor = new $.fn.dataTable.Editor({
table: "#remoteSqlDatabaseTable",
ajax: $("#UpdateIntegrationRemoteSqlDatabaseAction").val(),
fields: [
{ label: 'Reference Name', name: 'Name' },
{ label: 'IP Address or Host', name: 'IpAddress' },
{ label: 'Port', name: 'Port' },
{ label: 'Username', name: 'UserCredential' },
{ label: 'Password', name: 'PasswordCredential', def: '' },
{ name: 'button' }
]
});
editor
.on('open', function (e, type) {
if (type === 'inline') {
// Listen for a tab key event when inline editing
$(document).on('keydown.editor', function (e) {
if (e.keyCode === 9 || e.keyCode === 13) {
editor.blur();
}
});
}
if (editor.s.includeFields[0] === 'PasswordCredential') {
editor.field(editor.s.includeFields[0]).val('');
}
})
.on('close', function () {
$(document).off('keydown.editor');
})
.on('preSubmit', function (e, edit) {
if (edit.data[1].PasswordCredential !== undefined) {
var value = edit.data[1].PasswordCredential;
// check for null or whitespace
if (typeof value === 'undefined' || value == null || value.replace(/\s/g, '').length < 1) {
editor.close();
return false;
}
}
});
// Configure inline editing columns
$('#remoteSqlDatabaseTable').on('click', 'tbody td:not(:last-child)', function (e) {
editor.inline(this, {
submitOnBlur: true
});
});
// Reload data on edit to handle reordering
//editor.on("submitSuccess", function () {
// var table = $('#databaseConnectionTable').DataTable();
// console.log('submitSuccess');
// table.ajax.reload(function () {
// initTableStyling();
// });
//})
// Initialize datatable
var table = $('#remoteSqlDatabaseTable').DataTable({
paging: false,
searching: false,
info: false,
ordering: false,
ajax: $("#GetIntegrationRemoteSqlDatabasesAction").val(),
dom: 'Bfrtip',
columns: [
{ data: 'Name' },
{ data: 'IpAddress' },
{ data: 'Port' },
{ data: 'UserCredential' },
{ data: 'PasswordCredential' },
{ data: null }
],
select: false,
responsive: false,
buttons: [],
columnDefs: [
{
targets: -1,
data: null,
render: function (data, type, row, meta) {
return '<button class="btn red" type="button">Delete</button>';
}
}
],
initComplete: function (settings, json) {
//initTableStyling();
}
});
Like i said, i am not sure exactly where the problem is coming from. The method that is breaking is the editor.on('presubmit'), where it check if(edit.data[1] . edit.data[1] is the object that only has a 5th element.
this is everything relating to the table whos editing is the problem.
Updated answer, this works with objects. It isn't a pretty as find filter answers but it simply works.
Loop through the object and set a value.
Since there is only one element, it will set the variable without overwriting anything.
testArray = {"5" : "test"};
var val = "";
for(key in testArray){val = testArray[key];}
console.log(val);
You can do this:
let [first_element] = your_array
I am using Datatables to display a table and I am pulling a list of datestimes from a MySQL database. These date times are not standard dates and look like this:
12/30/19 # 04:17 pm
How can I sort these accurately with Datatables?
Here is my code:
getRes(function (result) { // APPLIED CALLBACK
$('#resdatatable').DataTable({
data: result, // YOUR RESULT
order: [[ 0, "desc" ]],
autoWidth: false,
responsive: true,
columns: [
{ data: 'id', title: 'ID' },
{ data: 'bookingdatetime', title: 'Booking Date' },
{ data: 'name', title: 'Name' },
{ data: 'class', title: 'Class' },
{ data: 'pickupdatetime', title: 'Pick up' },
{ data: 'duration', title: 'Duration' },
{ data: 'dropdatetime', title: 'Drop off' },
{ data: 'age', title: 'Age' },
{ data: 'coverage', title: 'Coverage' },
{ data: 'quote', title: 'Quote' },
{
data: 'status',
title: 'Status',
render: function(data, type, row) {
let isKnown = statusList.filter(function(k) { return k.id === data; }).length > 0;
if (isKnown) {
return $('<select id="resstatus'+row.id+'" onchange="changeResStatus('+row.id+')" data-previousvalue="'+row.status+'">', {
id: 'resstatus-' + row.id, // custom id
value: data
}).append(statusList.map(function(knownStatus) {
let $option = $('<option>', {
text: knownStatus.text,
value: knownStatus.id
});
if (row.status === knownStatus.id) {
$option.attr('selected', 'selected');
}
return $option;
})).on('change', function() {
changeresstatus(row.id); // Call change with row ID
}).prop('outerHTML');
} else {
return data;
}
}
}
]
});
});
/**
* jQuery plugin to convert text in a cell to a dropdown
*/
(function($) {
$.fn.createDropDown = function(items) {
let oldTxt = this.text();
let isKnown = items.filter(function(k) { return k.id === oldTxt; }).length > 0;
if (isKnown) {
this.empty().append($('<select>').append(items.map(function(item) {
let $option = $('<option>', {
text: item.text,
value: item.id
});
if (item.id === oldTxt) {
$option.attr('selected', 'selected');
}
return $option;
})));
}
return this;
};
})(jQuery);
// If you remove the renderer above and change this to true,
// you can call this, but it will run once...
if (false) {
$('#resdatatable > tbody tr').each(function(i, tr) {
$(tr).find('td').last().createDropDown(statusList);
});
}
function getStatusList() {
return [{
id: 'Confirmed',
text: 'Confirmed'
}, {
id: 'Unconfirmed',
text: 'Unconfirmed'
}, {
id: 'Communicating',
text: 'Communicating'
}, {
id: 'Open',
text: 'Open'
}, {
id: 'Closed',
text: 'Closed'
}, {
id: 'Canceled',
text: 'Canceled'
}, {
id: 'Reallocated',
text: 'Reallocated'
}, {
id: 'No Show',
text: 'No Show'
}];
}
I need to sort bookingdatetime, pickupdatetime, dropdatetime accurately (they are currently being converted into MM/DD/YY in the PHP script)
Maybe you can prepend hidden <span> elements containing the respective unix timestamps in the cells that have dates (by manually parsing the dates). Then using such columns to sort alphabetically would practically sort time-wise.
I am trying to use multiselector from EXTJS 6.5.2
This is the code that I am using to create multiselector with the values that I need
{
xtype: 'multiselector',
title: 'I caktohet:',
name: 'Caktohen[]',
bind: '{userfullname.value}',
fieldName: 'userfullname',
viewConfig: {
deferEmptyText: false,
emptyText: 'Askush i zgjedhur'
},
search: {
field: 'userfullname',
model: 'InTenders.model.UserModel',
store: {
type: 'users',
sorters: 'userfullname',
// proxy: {
// type: 'rest',
// limitParam: null,
// url: 'api/User'
// }
}
}
}
When I call form = win.down('form') records I can get all values except the multiselector values, they show like this on console.
Anyone can help me or guide me how to get the values?
Thank you.
//Code that I'm trying to get multiselector items and save them
saveTenderForm: function (button, e, eOpts) {
var userMultiSelector = Ext.getCmp('AssignedUsers'); //save assigned users
var selectedUsers = userMultiSelector.getStore().getData(); //get store and put them in array
var me = this,
win = button.up('window'),
form = win.down('form'),
// formApplyUpload = this.getFormApplyUpload(),
// var ko = win.items.items[0].items.items[0].value;
recordtenderUsers = Ext.create('InTenders.model.TenderSaveModel');
// recordtenderUsers = form.getRecord();
// record = form.getRecord(),
values = form.getValues();
// appFile = this.getApplicationFile(),
// callbacks;
recordtenderUsers.set(values);
recordtenderUsers.set('tenderUsers',selectedUsers.items);
// // me.showMask();
// if (form.isValid()) {
recordtenderUsers.save({
success: function (recordtenderUsers, operation) {
win.close();
me.hideMask();
},
failure: function (recordtenderUsers, operation) {
me.hideMask();
}
});
You can get value using multiselector.down('grid') this will return you the grid. And grid have method getSelection().
In this FIDDLE, I have created a demo. I hope this will help/guide you to achieve your requirement.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.create({
xtype: 'form',
renderTo: Ext.getBody(),
items: [{
xtype: 'multiselector',
title: 'Multi selector example',
fieldName: 'text',
viewConfig: {
deferEmptyText: false,
emptyText: 'No value selected'
},
search: {
field: 'text',
store: {
fields: [{
name: 'text',
type: 'string'
}],
data: [{
text: 'ABC'
}, {
text: 'ABC 1'
}, {
text: 'ABC 2 '
}, {
text: 'ABC 3'
}, {
text: 'ABC 4'
}]
}
}
}, {
xtype: 'button',
text: 'Get Value',
margin:15,
handler: function (btn) {
var multiselector = btn.up('form').down('multiselector');
if (multiselector.down('grid')) {
multiselector.down('grid').getSelection().forEach(rec => {
console.log(rec.get('text'));
});
}
}
}]
});
}
});
I want to filter my grid with different buttons that active certain filters. However they do not work on page load. Only when you select/deselect a filter option and then click the button, does the filter actually kick in.
When the page first loads and you click a button, you get the following error:
TypeError: filter is undefined
How do I enable these filter settings when the page first loads?
To recreate the error. Load the fiddle and try clicking the buttons and notice they don't work. Then activate one of the filters and try again. The buttons will work after a filter is activated.
Fiddle
Buttons
var openButton = Ext.create('Ext.Button', {
text: 'Open Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
filter.setActive(true);
filter.setValue('Open/Current');
}
});
var holdButton = Ext.create('Ext.Button', {
text: 'On Hold Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
filter.setActive(true);
filter.setValue('Hold');
}
});
var closedButton = Ext.create('Ext.Button', {
text: 'Closed Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
filter.setActive(true);
filter.setValue('Archived/Closed');
}
});
Columns
columns: [{
text: 'Title',
width: 260,
dataIndex: 'Title',
filterable: true,
filter: {
type: 'string'
// specify disabled to disable the filter menu
//, disabled: true
}
}, {
text: 'Description',
flex: 1,
dataIndex: 'Description',
filter: {
type: 'string'
// specify disabled to disable the filter menu
//, disabled: true
}
}, {
text: 'Modified',
width: 90,
dataIndex: 'Modified',
xtype: 'datecolumn',
format: 'm/d/Y',
filter: true
}, {
text: 'Status',
width: 100,
dataIndex: 'TopicStateValue',
filter: {
active: true,
type: 'list',
value: 'Open/Current',
options: ['Open/Current', 'Archived/Closed', 'Hold']
}
}]
Just check if the filter exists before pass value to it, if not, add it like this:
var openButton = Ext.create('Ext.Button', {
text: 'Open Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
if (!filter) {
filter = grid[uniqueId].filters
.addFilter({
type : 'string',
dataIndex : 'TopicStateValue'
});
}
filter.setActive(true);
filter.setValue('Open/Current');
}
});
var holdButton = Ext.create('Ext.Button', {
text: 'On Hold Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
if (!filter) {
filter = grid[uniqueId].filters
.addFilter({
type : 'string',
dataIndex : 'TopicStateValue'
});
}
filter.setActive(true);
filter.setValue('Hold');
}
});
var closedButton = Ext.create('Ext.Button', {
text: 'Closed Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
if (!filter) {
filter = grid[uniqueId].filters
.addFilter({
type : 'string',
dataIndex : 'TopicStateValue'
});
}
filter.setActive(true);
filter.setValue('Archived/Closed');
}
});
You need to initialize the filters manually before you use them.
Please add the below code to your grid panel.
listeners: {
beforeRender:function() {
this.filters.createFilters();
}
},
I tried that on your fiddle and it works.
I am trying to create dynamic listbox values but getting this error in console:
Uncaught TypeError: Cannot assign to read only property 'active' of [
Here's my code( pasting only the code for listbox ):
body: [
{
type: 'listbox',
name: 'type',
label: 'Panel Type',
value: type,
'values': get_author_list(),
tooltip: 'Select the type of panel you want'
},
]
.....
And I am calling this function to get dynamic list...
function get_author_list() {
var d = "[{text: 'Default', value: 'default'}]";
return d;
}
I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax?
Thanks, in advance!!
I needed something similar for .NET site. Even though is not great code I hope it can help someone.
tinymce.PluginManager.add('DocumentSelector', function (editor, url) {
// Add a button that opens a window
editor.addButton('DocumentSelector', {
text: 'Document',
icon: false,
title: "Document Selector",
onclick: function () {
var _documentList;
//load all documents
var _data = JSON.stringify({/* Some data */});
$.ajax({
type: "POST",
url: "/api/TinyMCE/GetDocuments",
data: _data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
_documentList = eval('(' + data + ')');
// Open window
editor.windowManager.open({
title: 'Document Selector',
body: [
{
type: 'listbox',
name: 'DocURL',
label: 'Documents',
values: _documentList
},
{
type: 'textbox'
, name: 'TextToDisplay'
, value: _text
, label: 'Text To Display'
},
{
type: 'textbox'
, name: 'TitleToDisplay'
, value: _title
, label: 'Title'
},
{
type: 'listbox',
name: 'TheTarget',
label: 'Target',
values: [{ text: 'None', value: "_self" }, { text: 'New Window', value: "_blank" }],
value: _target
}
],
onsubmit: function (e) {
// Insert content when the window form is submitted
}
});
},
error: function (xhr, status, error) {
alert("Error! " + xhr.status + "\n" + error);
}
});
}
});
});
And here it is some of the Behind code
public class TinyMCEController : ApiController
{
public class DocumentsInfo
{
// Some data
}
public class DocumentList
{
public string text { get; set; }
public string value { get; set; }
}
[HttpPost]
[ActionName("GetDocuments")]
public object GetDocuments(DocumentsInfo docInfo)
{
//Test data
List<DocumentList> _DocumentList = new List<DocumentList>();
_DocumentList.Add(new DocumentList {
text = "Document1.pdf",
value = "value1"
});
_DocumentList.Add(new DocumentList
{
text = "Document2.pdf",
value = "value2"
});
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(_DocumentList);
return json;
}
}