Custom datepicker on cell edit with ag-grid - javascript

I am trying to implement a date picker on cell edit. i have tried the below example
https://www.ag-grid.com/javascript-grid-cell-editing/#example-datepicker-cell-editing
This example used jquery-ui datepicker
function getDatePicker() {
function Datepicker() {}
Datepicker.prototype.init = function(params) {
this.eInput = document.createElement("input");
this.eInput.value = params.value;
$(this.eInput).datepicker({ dateFormat: "dd/mm/yy" });
};
Datepicker.prototype.getGui = function() {
return this.eInput;
};
Datepicker.prototype.afterGuiAttached = function() {
this.eInput.focus();
this.eInput.select();
};
Datepicker.prototype.getValue = function() {
return this.eInput.value;
};
Datepicker.prototype.destroy = function() {};
Datepicker.prototype.isPopup = function() {
return false;
};
return Datepicker;
}
This line
$(this.eInput).datepicker({ dateFormat: "dd/mm/yy" });
is used to add jquery-ui datepicker
How can i have a custom DatePicker react component that i want to include instead of jquery-ui datepicker ?

You need to implement interface ICellEditorComp {...} a Doc about custom editors is here https://www.ag-grid.com/javascript-grid-cell-editor/

Sample code from https://www.ag-grid.com/javascript-grid-cell-editing/#example-datepicker-cell-editing is written in a way it supports Jquery UI Datepicker in react project.
I have a suggested solution that i have tried with TextField Material UI and Material UI Native DatePicker.
Kindly check below code it worked well for me.
const getDatePicker = () => {
function Datepicker() {}
Datepicker.prototype.init = function(params) {
const fillZeros = (a) => {
return (Number(a) < 10) ? '0' + a : a;
}
const getFormatedDate = (dateString ) => {
const dateParse = new Date(dateString.split('/')[1]+'-' + dateString.split('/')[0]+'-'+dateString.split('/')[2]);
const dd = dateParse.getDate();
const mm = dateParse.getMonth() + 1; //January is 0!
const yyyy = dateParse.getFullYear();
console.log(dateString, yyyy + '-' + fillZeros(mm) + '-' + fillZeros(dd));
return yyyy + '-' + fillZeros(mm) + '-' + fillZeros(dd);
}
this.textInput = React.createRef();
const eInput = React.createElement(TextField, {
type: "date",
defaultValue: getFormatedDate(params.value),
ref: this.textInput
});
this.div = document.createElement('div');
this.div.className = "ag-cell-parent-append";
ReactDOM.render(eInput, this.div);
};
Datepicker.prototype.getGui = function() {
return this.div;
};
Datepicker.prototype.afterGuiAttached = function() {
this.textInput.current.focus();
};
Datepicker.prototype.getValue = function() {
return this.textInput.current.querySelector('input').value;
};
Datepicker.prototype.destroy = function() {};
Datepicker.prototype.isPopup = function() {
return false;
};
return Datepicker;
}
Full working example is in stackblitz

Related

JavaScript - prototype not returning functions - this.registerSelectors() is not a function - no Constructor

In our VS solution project, there are about 50 different JS files. What I am doing is moving the code out of these files (Require.js was used in these separated files) and combining all the code into one larger single JS file. Reason for this is to reduce the requests from the website.
Nonetheless, I am receiving 1 of 2 errors, depending on if I wrap the JS functions/prototypes w/ a self-containing function.
The code uses jQuery and jQuery.UI
First error (if wrapped) is FormBuilderDatePicker is not a constructor
Second error (if not wrapped) is this.registerSelectors is not a function
Calling JS code:
var quoteModuleObjArr = [
{ formId: "quote-module-form-moving", className: '.zipcode-moving', moveType: 'moving' },
{ formId: "quote-module-form-storage", className: '.zipcode-storage', moveType: 'storage' },
{ formId: "quote-module-form-moving-storage", className: '.zipcode-moving-storage', moveType: 'moving-storage' }
];
for (var i = 0; i < quoteModuleObjArr.length; i++) {
var formBuilder = null;
formBuilder = new FormBuilderDatePicker({
datepicker: '#' + quoteModuleObjArr[i].formId + ' input.isDatePicker',
formId: '#' + quoteModuleObjArr[i].formId
});
}
FormBuilderDatePicker function/prototype (wrapped):
var FormBuilderDatePicker = (function () { // remove for the 2nd error (unwrapped)
function FormBuilderDatePicker(options) {
this.options = options;
this.options = $.extend(true, {}, this.defaults, this.options);
this.registerSelectors();
this.delegateEvents()
};
FormBuilderDatePicker.prototype.defaults = {
datepicker: ".hasDatePicker",
disabledDays: [],
datepickerOptions: {
minDate: 0,
maxDate: "+12M"
},
formId: ''
};
FormBuilderDatePicker.prototype.registerSelectors = function () {
this.options.$datepicker = $(this.options.datepicker);
};
FormBuilderDatePicker.prototype.delegateEvents = function () {
var _self = this;
this.options.$datepicker.on("error", function () {
var selectedDate = _self.options.$datepicker.val();
_self.options.disabledDays.push(selectedDate)
});
this.options.$datepicker.on("change", function () {
$(this).valid()
});
this.options.datepickerOptions.beforeShowDay = function (date) {
var today = new Date;
var todayDate = $.datepicker.formatDate("mm/dd/yy", today);
var selectedDate = $.datepicker.formatDate("mm/dd/yy", date);
var notToday = todayDate != selectedDate;
var isDisabledDay = $.inArray($.datepicker.formatDate("m/d/yy", date), _self.options.disabledDays) == -1;
var result = notToday && isDisabledDay;
if (notToday == false) {
setTimeout(function () {
$(".ui-datepicker-today").removeClass("ui-state-disabled");
}, 0);
return [result, "ui-datepicker-current-day"];
}
return [result];
};
this.options.datepickerOptions.onChangeMonthYear = function (year, month, datepicker) {
}
this.options.$datepicker.datepicker(this.options.datepickerOptions);
};
return FormBuilderDatePicker; // remove for the 2nd error (unwrapped)
})(); // remove for the 2nd error (unwrapped)
I have also tried creating an init function, that calls FormBuilderDatePicker.registerSelectors() and FormBuilderDatePicker.delegateEvents(), and removed the last (2) lines within the constructor, but I get the same error, that registerSelectors() is not a function (same w/ delagateEvents().
I've also read that for prototypes to have the ability to be called, they need a return within the function. Hence, during testing, I added a return true; to the delegateEvents and registerSelectors functions, but this did not work either.
All code above is inside a $(function() {});
Updated Code/Solution:
setupFormBuilderDatePicker();
setupQuoteModuleDatePicker();
// ***********************************************
// Quote Module Date Picker
// ***********************************************
var FormBuilderDatePicker;
function setupFormBuilderDatePicker() {
FormBuilderDatePicker = (function () {
function FormBuilderDatePicker(options) {
this.options = options;
this.options = $.extend(true, {}, this.defaults, this.options);
this.registerSelectors();
this.delegateEvents()
};
FormBuilderDatePicker.prototype.defaults = {
datepicker: ".hasDatePicker",
disabledDays: [],
datepickerOptions: {
minDate: 0,
maxDate: "+12M"
},
formId: ''
};
FormBuilderDatePicker.prototype.registerSelectors = function () {
this.options.$datepicker = $(this.options.datepicker);
};
FormBuilderDatePicker.prototype.delegateEvents = function () {
var _self = this;
this.options.$datepicker.on("error", function () {
var selectedDate = _self.options.$datepicker.val();
_self.options.disabledDays.push(selectedDate)
});
this.options.$datepicker.on("change", function () {
$(this).valid()
});
this.options.datepickerOptions.beforeShowDay = function (date) {
var today = new Date;
var todayDate = $.datepicker.formatDate("mm/dd/yy", today);
var selectedDate = $.datepicker.formatDate("mm/dd/yy", date);
var notToday = todayDate != selectedDate;
var isDisabledDay = $.inArray($.datepicker.formatDate("m/d/yy", date), _self.options.disabledDays) == -1;
var result = notToday && isDisabledDay;
if (notToday == false) {
setTimeout(function () {
$(".ui-datepicker-today").removeClass("ui-state-disabled");
}, 0);
return [result, "ui-datepicker-current-day"];
}
return [result];
};
this.options.datepickerOptions.onChangeMonthYear = function (year, month, datepicker) {
}
this.options.$datepicker.datepicker(this.options.datepickerOptions);
};
return FormBuilderDatePicker;
})();
}
function setupQuoteModuleDatePicker() {
var quoteModuleObjArr = [
{ formId: "quote-module-form-moving", className: '.zipcode-moving', moveType: 'moving' },
{ formId: "quote-module-form-storage", className: '.zipcode-storage', moveType: 'storage' },
{ formId: "quote-module-form-moving-storage", className: '.zipcode-moving-storage', moveType: 'moving-storage' }
];
for (var i = 0; i < quoteModuleObjArr.length; i++) {
var formBuilder = null;
formBuilder = new FormBuilderDatePicker({
datepicker: '#' + quoteModuleObjArr[i].formId + ' input.isDatePicker',
formId: '#' + quoteModuleObjArr[i].formId
});
greyOutFacilityClosedDates(quoteModuleObjArr[i].formId, quoteModuleObjArr[i].className, formBuilder, quoteModuleObjArr[i].moveType);
//return formBuilder;
}
}
Just for testing purposes the OP's above posted code was taken as is ... results/conclusion ...
FormBuilderDatePicker exists as constructor function.
registerSelectors exists as prototypal method.
There was another error within the code of the prototypal delegateEvents methods though ... this.options.$datepicker.datepicker ... of cause is not provided with the current environment (settings).
The OP's script got sanitized and (re)formatted into the next provided example code in order to provide proof that the OP's code actually does work. Thus there must be some other reasons for the OP's script failures.
const dp = new FormBuilderDatePicker;
console.log({ registerSelectors: dp.registerSelectors });
console.log({ dp });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var FormBuilderDatePicker = (function () {
function FormBuilderDatePicker(options) {
this.options = options;
this.options = $.extend(true, {}, this.defaults, this.options);
this.registerSelectors();
this.delegateEvents();
};
FormBuilderDatePicker.prototype.defaults = {
datepicker: ".hasDatePicker",
disabledDays: [],
datepickerOptions: {
minDate: 0,
maxDate: "+12M",
},
formId: '',
};
FormBuilderDatePicker.prototype.registerSelectors = function () {
this.options.$datepicker = $(this.options.datepicker);
};
FormBuilderDatePicker.prototype.delegateEvents = function () {
var _self = this;
this.options.$datepicker.on("error", function () {
var selectedDate = _self.options.$datepicker.val();
_self.options.disabledDays.push(selectedDate);
});
this.options.$datepicker.on("change", function () {
$(this).valid();
});
this.options.datepickerOptions.beforeShowDay = function (date) {
var today = new Date;
var todayDate = $.datepicker.formatDate("mm/dd/yy", today);
var selectedDate = $.datepicker.formatDate("mm/dd/yy", date);
var notToday = todayDate != selectedDate;
var isDisabledDay = $.inArray($.datepicker.formatDate("m/d/yy", date), _self.options.disabledDays) == -1;
var result = notToday && isDisabledDay;
if (notToday == false) {
setTimeout(function () {
$(".ui-datepicker-today").removeClass("ui-state-disabled");
}, 0);
return [result, "ui-datepicker-current-day"];
}
return [result];
};
this.options.datepickerOptions.onChangeMonthYear = function (year, month, datepicker) {
};
// this.options.$datepicker.datepicker(this.options.datepickerOptions);
};
return FormBuilderDatePicker;
}());
</script>

Get values from inside a nested function using this

I have a piece of code which has two nested functions inside a main one.
How do I retrieve the nested functions using this keyword? Is it possible?
I have tried times().present() and new times().present() , none of them seem to work and return undefined.
I have found similar examples on w3School but cant seem to implement it in this case.
Thanks in advance.
function times() {
var timingObj = function() {
this.present = currentTime;
this.past = pastTime;
};
var currentTime = function() {
var hourMin = new Date().getHours() + ":" + new Date().getMinutes();
return hourMin;
};
var pastTime = function() {
if (new Date().getDay() == 5) {
return "07:40"
} else {
return "16:30"
}
};
return timingObj;
}
console.log(times().present());
//console.log(new times().present());
function times() {
var currentTime = function() {
var hourMin = new Date().getHours() + ":" + new Date().getMinutes();
return hourMin;
};
var pastTime = function() {
if (new Date().getDay() == 5) {
return "07:40"
} else {
return "16:30"
}
};
return {
present: currentTime,
past: pastTime
};
}
console.log(times().present())
You can use Method call().
function times() {
var timingObj = function() {
this.present = currentTime;
this.past = pastTime;
};
var currentTime = function() {
var hourMin = new Date().getHours() + ":" + new Date().getMinutes();
return hourMin;
};
var pastTime = function() {
if (new Date().getDay() == 5) {
return "07:40"
} else {
return "16:30"
}
};
return timingObj;
}
times().call(null);
console.log(present(), past());
OR define them as prototype
function times() {
var timingObj = function() {
this.present = timingObj.prototype.currentTime;
this.past = timingObj.prototype.pastTime;
};
timingObj.prototype.currentTime = function() {
return new Date().getHours() + ":" + new Date().getMinutes();
};
timingObj.prototype.pastTime = function() {
return new Date().getDay() === 5 ? "07:40" : "16:30";
};
return timingObj;
}
console.log(times().prototype.currentTime(), times().prototype.pastTime());
//times().call(null);
//console.log(present(), past());

The angular datepicker totally mis-behavior as expectation

I ran into a deadly chaos on datepicker issues.
Who can solve my problem I can give 100 point as a return.
When I click the calendar on 2016-08-23 it will show me the 2016-08-22 as the date value.
Furthermore, the date value in angular model is also not correct.
I want to make the output can be consistent.
To reproduce the buggy issue, change your timezone between LA and TOKYO
DEMO site: https://test.jiyubi.com/tour_package/home
controller js
app.controller('tourPackageStartDatePickerCtrl',
function ($scope) {
$scope.initStartDate = function () {
$scope.startDate = $scope.startDate || null;
};
$scope.initStartDate();
$scope.dateOptions = {
baseDate: $scope.startDate,
minDate: $scope.startDate || moment.utc().toDate(),
};
$scope.openStartDateClick = function () {
$scope.startDatePopup.opened = true;
};
});
app.controller('tourPackageEndDatePickerCtrl',
function ($scope, $rootScope) {
$scope.clear = function () {
$scope.endDate = null;
};
$scope.endDateOptions = {
dateDisabled: disabledDays,
baseDate: new Date(),
};
$scope.openEndDateClick = function () {
$scope.endDatePopup.opened = true;
};
$scope.$watch("endDate", function (new_val, old_val) {
if (new_val && moment(new_val).isValid()) {
setTravelDateRange($scope.startDate, $scope.endDate);
}
}, true)
function setTravelDateRange(startDate, endDate) {
var start_date = moment_with_TAIPEI_TZ(startDate).format("YYYY/MM/DD");
var end_date = moment_with_TAIPEI_TZ(endDate).format("YYYY/MM/DD");
moment(startDate.toDateString()).tz("Asia/Taipei").format("YYYY/MM/DD");
$scope.q_param.startDate = start_date;
$scope.q_param.date_range = start_date + "-" + end_date;
}
});
helper.js
function moment_with_TAIPEI_TZ(time){
return moment(time).tz("Asia/Taipei");
}
function MOMENT_WITH_LOCAL(time){
return moment(time).local();
}
function discard_timezone(value) {
return moment.utc(value).format(DEFAULT_MOMENT_TIME_FORMAT);
}
function getYYYYMMDD(value) {
return moment.utc(value).format("YYYY/MM/DD");
}
function date_without_timezone(value) {
return moment.utc(value).toDate();
}
It's may be because of a timezone issue.
Could you please try to convert to date without considering the timezone?
this.convertToDateWithoutTimezone = function(date) {
if (date.toString().match(/(\d\d\d\d)-(\d\d)-(\d\d)/)) {
var year = $filter('date')(date.slice(0, 10), 'yyyy'),
month = $filter('date')(date.slice(0, 10), 'MM'),
day = $filter('date')(date.slice(0, 10), 'dd');
return new Date(year, month - 1, day);
} else {
return new Date(date);
}
};

Input Calendar jumping to next input

I'm using this Calendar, and "i'm forced to use it" and i'm wondering if you could help me sorting out a small issue i'm having.
Calendar: http://www.bulgaria-web-developers.com/projects/javascript/calendar/
I have 2 input fields that this calendar is on,
<input type="text" id="cr_date_from" />
<input type="text" id="cr_date_to" />
And after selecting the date in "date_from" i need it to jump to "date_to" and have the same date as selected in the date_from field. As this will not cause confusion when people are selecting a date months ahead in time, and not to scroll all the way to that date in the date_to as well...
I've tried researching on this for a while now without luck, so i'm hoping you guys are able to help me out..
Appreciate all help on this!
Here is also the javascript for those interested...
bindSearch: function () {
var self = this,
dateFrom = new Calendar({
element: "cr_date_from",
//dateFormat: "Y-m-d",
dateFormat: self.opts.dateFormat,
monthNamesFull: self.opts.monthNamesFull,
dayNames: self.opts.dayNames,
disablePast: true,
months: 3,
onSelect: function () {
reCalc.call(self);
}
}),
dateTo = new Calendar({
element: "cr_date_to",
//dateFormat: "Y-m-d",
dateFormat: self.opts.dateFormat,
monthNamesFull: self.opts.monthNamesFull,
dayNames: self.opts.dayNames,
disablePast: true,
months: 3,
onSelect: function () {
reCalc.call(self);
}
}),
lnkFrom = document.getElementById("crDateFrom"),
lnkTo = document.getElementById("crDateTo"),
btnQuote = document.getElementById("crBtnQuote"),
btnMap = document.getElementById("crBtnMap"),
sameLoc = document.getElementById("cr_same_location"),
returnLoc = document.getElementById("crReturnBox");
self.elFrom = document.getElementById("cr_date_from");
self.elTo = document.getElementById("cr_date_to");
self.elHFrom = document.getElementById("cr_hour_from");
self.elMFrom = document.getElementById("cr_minutes_from");
self.elHTo = document.getElementById("cr_hour_to");
self.elMTo = document.getElementById("cr_minutes_to");
function reCalc() {
var from = Date.parseExact(this.elFrom.value, dateFormat(self.opts.dateFormat, 'datejs')).getTime() + (parseInt(this.elHFrom.value, 10) * 3600000) + (parseInt(this.elMFrom.value, 10) * 60000),
to = Date.parseExact(this.elTo.value, dateFormat(self.opts.dateFormat, 'datejs')).getTime() + (parseInt(this.elHTo.value, 10) * 3600000) + (parseInt(this.elMTo.value, 10) * 60000),
nd = document.getElementById("crNumDays"),
days;
if (from !== null && to !== null) {
days = Math.ceil((to - from) / 86400000);
if (days > 0) {
nd.lastChild.innerHTML = days;
nd.style.display = "";
} else {
nd.style.display = "none";
}
} else {
nd.style.display = "none";
}
}
if (lnkFrom) {
lnkFrom.onclick = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
dateFrom.isOpen ? dateFrom.close() : dateFrom.open();
return false;
};
}
if (lnkTo) {
lnkTo.onclick = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
dateTo.isOpen ? dateTo.close() : dateTo.open();
return false;
};
}
if (btnMap) {
btnMap.onclick = function (e) {
self.overlayMap.open();
if (e && e.preventDefault) {
e.preventDefault();
}
return false;
}
}
if (sameLoc && returnLoc) {
function bindLoc(el) {
if (this.checked) {
el.style.display = "none";
} else {
el.style.display = "";
}
}
sameLoc.onchange = function () {
bindLoc.call(this, returnLoc);
};
sameLoc.onclick = function () {
bindLoc.call(this, returnLoc);
};
}
if (btnQuote) {
btnQuote.onclick = function () {
this.disabled = true;
if (!self.validateSearch(this)) {
this.disabled = false;
return;
}
self.passed.first = true;
self.loadCars.apply(self, [JABB.Utils.serialize(document.getElementById("crFormSearch"))]);
};
}
},

Slickgrid, column with a drop down select list?

Hi I was wondering if anyone knows if it's possible to define a column in slickgrid as being a drop down select list. If not does anyone with some experience with slickgrid know how I should go about adding this option?
Thanks
You probably dont want to make a new select editor for each range of options. Also you may not know that range of all option value beforehand.
In that case you want a flexible range of options in a select type editor. In order to do this you can add an extra option to your column definitions (e.g. called options) like this:
var columns = [
{id:"color", name:"Color", field:"color", options: "Red,Green,Blue,Black,White", editor: SelectCellEditor},
{id:"lock", name:"Lock", field:"lock", options: "Locked,Unlocked", editor: SelectCellEditor}
]
and access that using args.column.options in the init method of your own SelectEditor object like this:
SelectCellEditor : function(args) {
var $select;
var defaultValue;
var scope = this;
this.init = function() {
if(args.column.options){
opt_values = args.column.options.split(',');
}else{
opt_values ="yes,no".split(',');
}
option_str = ""
for( i in opt_values ){
v = opt_values[i];
option_str += "<OPTION value='"+v+"'>"+v+"</OPTION>";
}
$select = $("<SELECT tabIndex='0' class='editor-select'>"+ option_str +"</SELECT>");
$select.appendTo(args.container);
$select.focus();
};
this.destroy = function() {
$select.remove();
};
this.focus = function() {
$select.focus();
};
this.loadValue = function(item) {
defaultValue = item[args.column.field];
$select.val(defaultValue);
};
this.serializeValue = function() {
if(args.column.options){
return $select.val();
}else{
return ($select.val() == "yes");
}
};
this.applyValue = function(item,state) {
item[args.column.field] = state;
};
this.isValueChanged = function() {
return ($select.val() != defaultValue);
};
this.validate = function() {
return {
valid: true,
msg: null
};
};
this.init();
}
I assume you mean a custom cell editor.
Here's a sample select-based boolean cell editor from slick.editors.js. You could easily modify it to work with an arbitrary set of possible values.
function YesNoSelectCellEditor($container, columnDef, value, dataContext) {
var $select;
var defaultValue = value;
var scope = this;
this.init = function() {
$select = $("<SELECT tabIndex='0' class='editor-yesno'><OPTION value='yes'>Yes</OPTION><OPTION value='no'>No</OPTION></SELECT>");
if (defaultValue)
$select.val('yes');
else
$select.val('no');
$select.appendTo($container);
$select.focus();
};
this.destroy = function() {
$select.remove();
};
this.focus = function() {
$select.focus();
};
this.setValue = function(value) {
$select.val(value);
defaultValue = value;
};
this.getValue = function() {
return ($select.val() == 'yes');
};
this.isValueChanged = function() {
return ($select.val() != defaultValue);
};
this.validate = function() {
return {
valid: true,
msg: null
};
};
this.init();
};
If your cell already contains a "select"-tag with multiple options, you can extract this html from the args. The approach differs from the previous answers, but I was personally troubled with these solutions, course my cell already contained a select-tag. I'd like to reuse this cell instead of reconstructing it completely in the this.init. Likewise, I'd like to keep using the same options, as my existing select already have, instead of parsing them to the var column = { ...
The $( args.item[ args.column.field ] ) return the active cells content, which basically just get re-appended to the the container (the cell-object). From if ( document.createEvent ) and down, is just a functionality which automatically opens the dropdown on activation; etc. when you use tabulator to navigate to the cell.
function SelectCellEditor( args ) {
var $select;
var defaultValue;
var scope = this;
this.init = function () {
$select = $( args.item[ args.column.field ] );
$select.appendTo( args.container );
$select.focus();
// Force the select to open upon user-activation
var element = $select[ 0 ];
if ( document.createEvent ) { // all browsers
var e = new MouseEvent( "mousedown", {
bubbles: true,
cancelable: true,
view: window
});
element.dispatchEvent( e );
} else if ( element.fireEvent ) { // ie
element.fireEvent( "onmousedown" );
}
};
}
Complet editor for Dropdown html-input -> Dropdown html-output
function SelectCellEditor( args ) {
var $select = $( args.item[ args.column.field ] );
var defaultValue;
var scope = this;
this.init = function () {
//$select
$select.appendTo( args.container );
// Force the select to open upon user-activation
var element = $select[ 0 ];
if ( document.createEvent ) { // all browsers
var e = new MouseEvent( "mousedown", {
bubbles: true,
cancelable: true,
view: window
});
element.dispatchEvent( e );
} else if ( element.fireEvent ) { // ie
element.fireEvent( "onmousedown" );
}
$select.on("click", function( e ) {
var selected = $( e.target ).val();
$select.find( "option" ).removeAttr( "selected" );
$select.find( "option[value='" + selected + "']" ).attr( "selected", "selected" );
});
};
this.destroy = function () {
$select.remove();
};
this.focus = function () { };
this.loadValue = function ( item ) { };
this.serializeValue = function () { };
// Only runs if isValueChanged returns true
this.applyValue = function ( item, state ) {
item[ args.column.field ] = $select[ 0 ].outerHTML;
};
this.isValueChanged = function () {
return true;
};
this.validate = function () {
return {
valid: true,
msg: null
};
};
this.init();
}
Without jq, and inline injected elements, packed in module:
'use strict';
class SelectCellWidget {
constructor(args) {
this._args = args;
this._$select = undefined;
this._defaultValue = undefined;
this._init();
}
_init () {
let selects, container, divend, opt_values;
const args = this._args;
if(args.column.options){
opt_values = args.column.options.split(',');
}else{
opt_values = ["yes","no"];
}
container = document.createElement("div");
container.classList.add('select-editable');
divend = document.createElement('input');
divend.setAttribute("type", "text");
divend.setAttribute("name", "format");
divend.setAttribute("value", "");
selects = document.createElement("select");//"<select id='Mobility' tabIndex='0' class='editor-select'>"+ option_str +"</select>";
selects.setAttribute("id", "Mobility");
selects.setAttribute("tabIndex", 0);
selects.setAttribute("class", "editor-select");
for(let i = 0; i < opt_values.length; i++) {
let v = opt_values[i];
let option = document.createElement("option");
option.setAttribute("value", v);
option.innerText = v;
selects.appendChild(option);
}
container.appendChild(divend);
container.appendChild(selects);
this._$select = container;
args.container[0].appendChild(this._$select);
this._$select.focus();
document.getElementById("Mobility").selectedIndex = args.item[args.column.field] ? opt_values.indexOf(args.item[args.column.field]) : 0;
}
destroy () {
this._$select.remove();
}
focus () {
this._$select.focus();
}
loadValue (item) {
this._defaultValue = item[this._args.column.field];
this._$select.value = this._defaultValue;
}
serializeValue () {
if(this._args.column.options){
return this._$select.lastElementChild.value;
}else{
return (this._$select.lastElementChild.value === "yes");
}
}
applyValue (item,state) {
item[this._args.column.field] = state;
}
isValueChanged () {
return (this._$select.lastElementChild.value !== this._defaultValue);
}
validate () {
return {
valid: true,
msg: null
};
}
}
module.exports=SelectCellWidget;
https://github.com/YaAlfred/SlickgridSelectDropdownWidget

Categories

Resources