select item by text with jshjohnson choices - javascript

How to realize selection of an item from choices element using jshjohnson choices library.
Code:
let vehicleModel = document.getElementById('vehicleModel');
let choiceProps = {
renderChoiceLimit: -1,
maxItemCount: -1,
silent: false,
removeItems: false,
editItems: false,
searchEnabled: true,
searchFields: 'label',
searchResultLimit: 6,
itemSelectText: 'Кликните для выбора',
classNames: {
listSingle: 'form-control pl-3',
containerInner: 'p-0'
},
};
const modelChoices = new Choices(vehicleModel, choiceProps);
let models = []; // I get the values from axios to pass them as paramater
modelChoices.setChoices(models, 'value', 'label', false);
After I initiated choices element in another part of code i have to select a value with autofilling function
const fillModelWithValue = (modelName) => {
let modelCoices = document.getElementById('vehicleModel').setChoiceByValue(modelName);
}
This code doesn't work. But how can I realize this functionality?

Related

ag-grid: Using Javascript, find the row id for a given data

I have a list of employees and I want to find the “id” of the row where firstName=Bob which is unique. In other words, I know the firstName supplied as “Bob” and now, I just need to find the row id using Javascript for ag-grid.
According to the documentation https://www.ag-grid.com/javascript-grid/accessing-data/ and I see that the rowNode can be got by using
getRowNodeId: data => data.id,
But I am just unable to to send the parameters (Bob), so that ag-grid finds and puts the id in some assigned variable. I think foreachloop is unnecessary to iterate each and every row, in case if the dataset is too big, then it will be an overhead.
I have the index.html file and a cellRenderer script as shown below. When the circle icon is clicked, I get the row Id correctly, but I am unable to retrieve the firstName, lastName etc.
I tried in two ways (i) writing the evenlistener inside the cellRenderer class, but most convenient for is to take this event listener as a function out of the cell Renderer file. (ii) So, I added a function called getAlert() which you can see as commented. Nothing works for me.
index.html
<div id="myGrid" style="height: 800px; width:100%;" class="ag-theme-alpine"></div>
<script>
var colSpan = function (params) {
return params.data === 2 ? 3 : 1;
};
const columnDefs = [
{ headerName:'FIRST NAME',field: "firstName", width:100, cellClass: 'my-class', colSpan: colSpan,},
{ headerName:'LAST NAME',field: "lastName", cellClass: 'my-class', flex: 6,},
{ headerName:'DESIGNATION (%)',field: "designation", cellClass: 'my-class', flex: 1,},
{ headerName:'INFO', field: "row_id",flex: 2, cellRenderer: 'infoCellRenderer'},
{ headerName:'COMMAND',field: "action",flex: 2,},
];
// let the grid know which columns and what data to use
const gridOptions = {
defaultColDef: {
resizable: true,
},
columnDefs: columnDefs,
getRowNodeId: data => data.id,
onGridReady: event => console.log('The grid is now ready'),
components:{
infoCellRenderer: InfoCellRenderer,
},
};
/*function getAlert(params)
{
console.log(params.node.firstName+","+params.firstName+","+params.value);
}*/
document.addEventListener('DOMContentLoaded', function () {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
//gridOptions.api.refreshView();
agGrid
.simpleHttpRequest({
url: 'XXXXXXX',
})
.then((data) => {
gridOptions.api.setRowData(data);
});
});
</script>
cellRenderer class
class InfoCellRenderer {
constructor() {}
// gets called once before the renderer is used
init(params) {
// create the cell
this.eGui = document.createElement('div');
this.eGui.innerHTML = '<i class="fas fa-info-circle"></i>';
// get references to the elements we want
this.circleValue = this.eGui.querySelector('.circle');
// add event listener to button
this.cellValue = this.getValueToDisplay(params);
//this.eventListener = () => getAlert('${params}');
this.eventListener = () => console.log(`${params.node.id},${params.node.firstName},${params.node.row_id}`);
this.circleValue.addEventListener('click', this.eventListener);
}
getGui() {
return this.eGui;
}
// gets called whenever the cell refreshes
refresh() {
// set value into cell again
this.cellValue = this.getValueToDisplay(params);
//this.eValue.innerHTML = this.cellValue;
// return true to tell the grid we refreshed successfully
return true;
}
// gets called when the cell is removed from the grid
destroy() {
// do cleanup, remove event listener from button
if(this.circleValue) {
// check that the button element exists as destroy() can be called before getGui()
this.circleValue.removeEventListener('click', this.eventListener);
}
}
getValueToDisplay(params) {
return params.valueFormatted ? params.valueFormatted : params.value;
}
}
if firstName is unique you can do as followed:
this.gridOptions.getRowNodeId = data => {
return data.firstName;
};
this code tells ag-grid to use firstName as its internal row Id. so you can easily get the row by:
const node = this.gridApi.getRowNode('Bob');
see link (note // ********* comments ) for full example
gridOptions.api.getModel().forEachNode(
function(rowNode, index){
if (rowNode.data.firstName == "Bob") {
row_index = index;
row = gridOptions.api.getModel().rowsToDisplay[row_index];
data_dict = row.data;
// do something with your row data, data_dict
}
}
);

How to get selected checkbox based on first selected dropdown after refresh the page?

I have dropdown, checkboxes and button submit. First, the user will choose at dropdown (position of work). Second, the user will select the checkbox and after that submit the data. Here, after refresh it should be appear back the previous selected dropdown and checkbox. But, I did not get it. Anyone here have more better solution?
JavaScript Dropdown
//dropdown position
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "../DesignationProgramTemplate/getData.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: onChange
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
Checkbox treeview (Kendo UI)
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot,
dataType: "json"
}
},
schema: {
model: {
id : "ehorsProgramID",
hasChildren: false,
children : "items"
}
},
filter: { field: "module", operator: "startswith", value: "Accounting" }
});
$("#AccountingTree").kendoTreeView({
check: onCheck,
checkboxes: { checkChildren: true } ,
// select: onSelect,
dataSource: homogeneous,
dataBound: function(){
this.expand('.k-item');
},
dataTextField: ["module","groupname","ehorsProgramName"]
});
AJAX for submit button
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/getTemplate.php",
type: "post",
data: {'id':test,'progid':array},
success: function () {
// you will get response from your php page (what you echo or print)
kendo.alert('Success'); // alert notification
//refresh
//location.reload("http://hq-global.winx.ehors.com:9280/ehors/HumanResource/EmployeeManagement/DesignationProgramTemplate/template.php");
},
});
});
JavaScript for check checkboxes
function checkedNodeIds(nodes, checkedNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].id);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
var array = [];
function onCheck() {
var checkedNodes = [],treeView = $("#AccountingTree").data("kendoTreeView"),message;
var checkedNodes2 = [],treeView2 = $("#AdminSystemTree").data("kendoTreeView"),message;
var checkedNodes3 = [],treeView3 = $("#FnBTree").data("kendoTreeView"),message;
var checkedNodes4 = [],treeView4 = $("#HumanResourceTree").data("kendoTreeView"),message;
var checkedNodes5 = [],treeView5 = $("#InventoryManagementTree").data("kendoTreeView"),message;
var checkedNodes6 = [],treeView6 = $("#SalesMarketingTree").data("kendoTreeView"),message;
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
checkedNodeIds(treeView2.dataSource.view(), checkedNodes);
checkedNodeIds(treeView3.dataSource.view(), checkedNodes);
checkedNodeIds(treeView4.dataSource.view(), checkedNodes);
checkedNodeIds(treeView5.dataSource.view(), checkedNodes);
checkedNodeIds(treeView6.dataSource.view(), checkedNodes);
if (checkedNodes.length > 0) {
message = checkedNodes.filter(x => !!x).join(",");
array = checkedNodes.filter(x => !!x);
} else {
message = "No nodes checked.";
}
}
Output
JavaScript for accessing the dataItem
// cookies
var values = ["LA1","LA6","LA12"]; //array nnti array ni la localstorage/cookies
var setTreeViewValues = function(values) {
var tv = $("#AccountingTree").data("kendoTreeView");
document.write(JSON.stringify(tv));
tv.forEach(function(dataItem) {
alert("test");
if (dataItem.hasChildren) {
var childItems = dataItem.children.data();
//document.write(JSON.stringify(childItems[0].items[0].programID));
}
// document.write(JSON.stringify(dataItem.items));
if (values.indexOf(childItems[0].items[0].programID) > -1) {
dataItem.set("checked", true);
}
});
};
setTreeViewValues(values);
console.log(datasource.data()[0].hasChildren);
// end cookies
So without knowing how you are binding the existing values to the page I am assuming you will be calling the page state somewhere within your Page loading.
So I have prepared a dojo that shows two different ways of setting the checked state of the items.
https://dojo.telerik.com/EhaMIDAt/8
1. Setting at the DataSource Level
So when setting up the datasource you can add an extra attribute to your collection called checked this will then set the checked value for the item or children items when loaded. using the example I have in the dojo:
{
id: 9,
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
id: 10,
text: "February.pdf",
spriteCssClass: "pdf"
},
{
id: 11,
text: "March.pdf",
spriteCssClass: "pdf",
checked: true
},
{
id: 12,
text: "April.pdf",
spriteCssClass: "pdf"
}
]
}
this will set the checked state to true for you and show the checkbox as checked.
2. Manually Set the values after loading all the DataSources.
So I have done this on a button click but this could easily be done on a ready state or some other trigger if needed. Here the button when clicked will find the node in the tree with the text Research.pdf and either set it in a checked or unchecked state for you.
$('#checked').bind('click', () => {
var box = $("#treeview").data("kendoTreeView").findByText('Research.pdf').find('input[type="checkbox"]');
box.prop('checked', !box.is(':checked'));
});
Again the sample it taken from dojo link above. Hopefully this gives you a start on getting the values set according to your specific requirements.
I would probably have the value checked state set when you load the datasource for the treeview.

Generating TinyMCE drop-down menu dynamically

I am trying to create toolbar button in TinyMCE with options that are derived from the array. I've followed the examples on Tiny's website and the button is getting generated as expected. Here is the code:
var mergeFields = {one: "first", two: "second", three: "third"};
tinymce.init({
selector: 'textarea',
menubar: false,
toolbar: 'mergefields',
setup: function (editor) {
editor.ui.registry.addMenuButton('mergefields', {
text: 'Merge Fields',
fetch: function (callback) {
var items = [];
for (var fieldName in mergeFields) {
var menuItem = {
type: 'menuitem',
text: mergeFields[fieldName],
onAction: function() {
// The problem: this function always inserts the last element of the array
// instead of the expected fieldName associated with this menuItem
editor.insertContent(fieldName);
},
};
items.push(menuItem);
}
callback(items);
},
});
}
});
<script src="https://cloud.tinymce.com/5/tinymce.min.js?apiKey=XXXXX"></script>
<textarea>Editor</textarea>
The problem happens when one of the options is selected and the anonymous function assigned to onAction property is executed -- it always inserts "three" into the document (presumably because after running through the whole array, fieldName is set to "three"). How can I make the onAction handler insert the right value into the document?
This needs to work in TinyMCE 5.
I've found a similar question here: Adding custom dropdown menu to tinyMCE and insert dynamic contents, but it was referring to TinyMCE 4 and unfortunately the provided answer does not work for TinyMCE 5.
Thanks for your help!
I had the same problem.
I solved it using value+onSetup
https://jsfiddle.net/stvakis/tjh7k20v/8/
var mergeFields = {
one: "first",
two: "second",
three: "third"
};
tinymce.init({
selector: 'textarea',
menubar: false,
toolbar: 'mergefields',
setup: function(editor) {
editor.ui.registry.addMenuButton('mergefields', {
text: 'Merge Fields',
fetch: function(callback) {
var items = [];
for (var fieldName in mergeFields) {
var menuItem = {
type: 'menuitem',
text: mergeFields[fieldName],
value:fieldName,
onSetup: function(buttonApi) {
var $this = this;
this.onAction = function() {
editor.insertContent($this.data.value);
};
},
};
items.push(menuItem);
}
callback(items);
},
});
}
});

Problem with variable scope in nested Backbone views

I have a parent view which contains a Backgrid view. In the parent view's initialize section I define a variable isWellSelected. The variable is toggled in the Backgrid column logic when a tickbox is checked. I am able to watch the variable toggled when a box is ticked and unticked.
However, once an event fires the variable is no longer in scope for the event to see. I suspect I may need to pass the variable to the Backrgrid view but I am unsure how to do that correctly. Please advise.
app.wellCollectionView = Backbone.View.extend({
template: _.template($('#wellTemplate').html()),
initialize: function() {
this.isWellSelected = false;
// isWellSelected toggled to true when a tickbox is checked in the columns block.
var columns = [...];
// instantiate collection
var wellCollection = new app.wellCollection;
// Set up a grid view to use the pageable collection
var wellGrid = new Backgrid.Grid({
columns: columns,
collection: wellCollection
});
// Initialize the paginator
var paginator = new Backgrid.Extension.Paginator({
collection: wellCollection
});
// Render the template
this.$el.html(this.template());
// Render the grid
this.$el.append(wellGrid.render().el);
this.$el.append(paginator.render().$el);
wellCollection.fetch({reset: true}).then(function () {...});
},
events: {
'click #EvaluateWell': function(){
this.evalWell(event, this.isWellSelected);
console.log("In events - isWellSelected: " + this.isWellSelected);}
},
// More stuff
}
Constructive feedback welcome.
Thanks!
Adding a snippet for "columns" as per JT's request:
var columns = [
{
name: '',
label: 'Select',
cell: Backgrid.BooleanCell.extend({
events : {
'change': function(ev){
var $checkbox = $(ev.target);
var $checkboxes = $('.backgrid input[type=checkbox]');
if($checkbox.is(':checked')) {
$checkboxes.attr("disabled", true);
this.isWellSelected = true;
// Disable all checkboxes but this one
$checkbox.removeAttr("disabled");
} else {
// Enable all checkboxes again
$checkboxes.removeAttr("disabled");
this.isWellSelected = false;
}
}
}
})
}, {
name: "api",
label: "API",
editable: false, // Display only!
cell: "string"
}, {
name: "company",
label: "Operator",
editable: false, // Display only!
cell: "string"
}];

How to disable default title block in Gutenberg with Javascript

Is there a way to disable the default title block in the Gutenberg editor with JavaScript? Couldn't find anything in the official API.
Something like a property in the settings object that you pass when setting up the Gutenberg.
Currently, I do like so (with the title):
const window = this.iframe.contentWindow // this.iframe is a React ref
const wpData = window.wp ? window.wp.data : false
if (!wpData) {
return
}
const newPost = Object.assign({ content: { raw: '', rendered: '' } }, window._wpGutenbergDefaultPost)
const editorSettings = {
alignWide: false,
availableTemplates: [],
blockTypes: true,
disableCustomColors: false,
disablePostFormats: false,
titlePlaceholder: '',
bodyPlaceholder: 'Add content here'
}
const editor = wpData.dispatch('core/editor')
editor.setupEditor(newPost, editorSettings)

Categories

Resources