When i delete the following "label" as a block using the backspace key, i would like to detect this event and do an ajax call, for example.
This part is deleted when i use backspace
Rendered
The problem is: there can be lots of labels (a tags) in textarea with different id's, i want to detect when any block is going to be deleted, save the id and remove.
Configuration
I'm using a custom configuration with a custom entity called annotation which represents the HTML above.
// Create CodeMirror (with lineWrapping on).
var codeMirror = CodeMirror(document.getElementById('firepad-container'), {lineWrapping: true});
// Create Firepad (with rich text toolbar and shortcuts enabled).
var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, {
richTextShortcuts: true,
richTextToolbar: true,
userId: userId,
userColor: userImage,
});
//// Create FirepadUserlist (with our userId, user name and avatar to display).
var firepadUserList = FirepadUserlist.fromDiv(firepadRef.child('users'),
document.getElementById('userlist'), userId, displayName, userImage);
firepad.registerEntity('annotation', {
render: function (info, entityHandler) {
var inputElement = document.createElement('a');
if(info.id) {
inputElement.setAttribute('id', info.id);
}
if(info.classList) {
inputElement.setAttribute('class', info.classList);
}
if(info.color || info.cursor) {
inputElement.setAttribute('style', 'color:' + info.color + '; cursor:' + info.cursor + ';');
}
inputElement.innerText = info.innerText;
inputElement.addEventListener('click', function(e){
editAnnotation(info.id, e);
entityHandler.remove();
});
return inputElement;
}.bind(this),
fromElement: function (element) {
var info = {};
if(element.hasAttribute('id')) {
info.id = element.id;
}
if(element.hasAttribute('class')) {
info.classList = element.classList;
}
info.color = element.style["color"];
info.cursor = element.style["cursor"];
info.innerText = element.innerText;
return info;
},
update: function (info, element, entityHandler) {
if(info.id) {
element.setAttribute('id', info.id);
}
if(info.classList) {
element.setAttribute('class', info.classList);
}
if(info.color || info.cursor) {
element.setAttribute('style', 'color:' + info.color + '; cursor:' + info.cursor + ';');
}
element.innerText = info.innerText;
},
export: function () {
var inputElement = document.createElement('a');
return inputElement;
}
});
If you want to add this new entity just use this:
firepad.insertEntity('annotation', { 'id': annotationId, 'color': color, 'cursor': 'pointer', 'innerText': 'whatever you want'});
Related
I am building a custom checkout where Stripe is handling the payment information. I'm using the Stripe Elements Library. When I was using the test publishable key I was about to get an input with a token but once I switched to the live key that was no longer happening. I'm not sure if there something missing in my setup that's not allowing the token to be generated when the live key is active.
Here's my Javascript for the Stripe Elements integrations
<script src="https://js.stripe.com/v3/"></script>
<script>
// Create a Stripe client.
var stripe = Stripe('pk_live_xxxxxxxxxxxxxx');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
},
':focus': {
color: '#333',
},
'::placeholder': {
color: '#333',
},
':focus::placeholder': {
color: '#333',
},
},
invalid: {
color: '#DC5B5B',
iconColor: '#DC5B5B',
':focus': {
color: '#DC5B5B',
},
'::placeholder': {
color: '#DC5B5B',
},
}
};
var elementClasses = {
focus: 'focus',
empty: 'empty',
invalid: 'invalid',
};
// Create an instance of the card Element.
var cardNumber = elements.create('cardNumber', {
style: style,
classes: elementClasses,
});
cardNumber.mount('#example3-card-number');
var cardExpiry = elements.create('cardExpiry', {
style: style,
classes: elementClasses,
});
cardExpiry.mount('#example3-card-expiry');
var cardCvc = elements.create('cardCvc', {
style: style,
classes: elementClasses,
});
cardCvc.mount('#example3-card-cvc');
registerElements([cardNumber, cardExpiry, cardCvc], 'example3');
function registerElements(elements, exampleName) {
var formClass = '.' + exampleName;
var example = document.querySelector(formClass);
var form = example.querySelector('form');
var resetButton = example.querySelector('a.reset');
var error = form.querySelector('.error');
var errorMessage = error.querySelector('.message');
function enableInputs() {
Array.prototype.forEach.call(
form.querySelectorAll(
"input[type='text'], input[type='email'], input[type='tel']"
),
function(input) {
input.removeAttribute('disabled');
}
);
}
function disableInputs() {
Array.prototype.forEach.call(
form.querySelectorAll(
"input[type='text'], input[type='email'], input[type='tel']"
),
function(input) {
input.setAttribute('disabled', 'true');
}
);
}
function triggerBrowserValidation() {
// The only way to trigger HTML5 form validation UI is to fake a user submit
// event.
var submit = document.createElement('input');
submit.type = 'submit';
submit.style.display = 'none';
form.appendChild(submit);
submit.click();
submit.remove();
}
// Listen for errors from each Element, and show error messages in the UI.
var savedErrors = {};
elements.forEach(function(element, idx) {
element.on('change', function(event) {
if (event.error) {
error.classList.add('visible');
savedErrors[idx] = event.error.message;
errorMessage.innerText = event.error.message;
} else {
savedErrors[idx] = null;
// Loop over the saved errors and find the first one, if any.
var nextError = Object.keys(savedErrors)
.sort()
.reduce(function(maybeFoundError, key) {
return maybeFoundError || savedErrors[key];
}, null);
error.classList.remove('visible');
if (nextError) {
// Now that they've fixed the current error, show another one.
errorMessage.innerText = nextError;
error.classList.add('visible');
} else {
// The user fixed the last error; no more errors.
error.classList.remove('visible');
}
}
});
});
// Listen on the form's 'submit' handler...
form.addEventListener('submit', function(e) {
e.preventDefault();
// Trigger HTML5 validation UI on the form if any of the inputs fail
// validation.
var plainInputsValid = true;
Array.prototype.forEach.call(form.querySelectorAll('input'), function(
input
) {
if (input.checkValidity && !input.checkValidity()) {
plainInputsValid = false;
return;
}
});
if (!plainInputsValid) {
triggerBrowserValidation();
return;
}
// Show a loading screen...
example.classList.add('submitting');
// Disable all inputs.
disableInputs();
// Gather additional customer data we may have collected in our form.
var name = form.querySelector('#' + exampleName + '-name');
var address1 = form.querySelector('#' + exampleName + '-address');
var city = form.querySelector('#' + exampleName + '-city');
var state = form.querySelector('#' + exampleName + '-state');
var zip = form.querySelector('#' + exampleName + '-zip');
var additionalData = {
name: name ? name.value : undefined,
address_line1: address1 ? address1.value : undefined,
address_city: city ? city.value : undefined,
address_state: state ? state.value : undefined,
address_zip: zip ? zip.value : undefined,
};
// Use Stripe.js to create a token. We only need to pass in one Element
// from the Element group in order to create a token. We can also pass
// in the additional customer data we collected in our form.
stripe.createToken(elements[0], additionalData).then(function(result) {
// Stop loading!
example.classList.remove('submitting');
if (result.token) {
stripeTokenHandler(result.token)
} else {
// Otherwise, un-disable inputs.
enableInputs();
}
});
});
}
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
}
I only made minor changes to the Javascript code above to match my html when I first implemented it other than that the code is exactly what I found and used when I had the test key.
I'm not very familar with Stripe's Element Library so any help would be greatly appreciated.
I'm looking for a way to add an extra button to L.control.zoom. Leaflet is being loaded from a CDN and I'm using vanilla Javascript (no preprocessors or anything).
I was hoping there'd be something like L.control.zoom.extend({}), but unfortunately that doesn't exist. Trying L.Control.extend({...L.control.zoom}) didn't work either.
For context, doing it the long way by copy-pasting the original code and adding the code for my custom button at line 42 would look like this:
let zoomControls = L.Control.extend({
// #section
// #aka Control.Zoom options
options: {
position: 'topleft',
// #option zoomInText: String = '+'
// The text set on the 'zoom in' button.
zoomInText: '+',
// #option zoomInTitle: String = 'Zoom in'
// The title set on the 'zoom in' button.
zoomInTitle: 'Zoom in',
// #option zoomOutText: String = '−'
// The text set on the 'zoom out' button.
zoomOutText: '−',
// #option zoomOutTitle: String = 'Zoom out'
// The title set on the 'zoom out' button.
zoomOutTitle: 'Zoom out'
},
onAdd: function (map) {
var zoomName = 'leaflet-control-zoom',
container = L.DomUtil.create('div', zoomName + ' leaflet-bar'),
options = this.options;
let locationLink = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container);
L.DomEvent.disableClickPropagation(locationLink);
locationLink.title = 'My location';
let locationIcon = L.DomUtil.create('span', 'fa-lg fas fa-map-marker-alt', locationLink);
L.DomEvent.on(locationLink, 'click', () => {
alert('BUTTON CLICKED');
});
this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
zoomName + '-in', container, this._zoomIn);
this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
zoomName + '-out', container, this._zoomOut);
this._updateDisabled();
map.on('zoomend zoomlevelschange', this._updateDisabled, this);
return container;
},
onRemove: function (map) {
map.off('zoomend zoomlevelschange', this._updateDisabled, this);
},
disable: function () {
this._disabled = true;
this._updateDisabled();
return this;
},
enable: function () {
this._disabled = false;
this._updateDisabled();
return this;
},
_zoomIn: function (e) {
if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
}
},
_zoomOut: function (e) {
if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
}
},
_createButton: function (html, title, className, container, fn) {
var link = L.DomUtil.create('a', className, container);
link.innerHTML = html;
link.href = '#';
link.title = title;
/*
* Will force screen readers like VoiceOver to read this as "Zoom in - button"
*/
link.setAttribute('role', 'button');
link.setAttribute('aria-label', title);
L.DomEvent.disableClickPropagation(link);
L.DomEvent.on(link, 'click', L.DomEvent.stop);
L.DomEvent.on(link, 'click', fn, this);
L.DomEvent.on(link, 'click', this._refocusOnMap, this);
return link;
},
_updateDisabled: function () {
var map = this._map,
className = 'leaflet-disabled';
L.DomUtil.removeClass(this._zoomInButton, className);
L.DomUtil.removeClass(this._zoomOutButton, className);
if (this._disabled || map._zoom === map.getMinZoom()) {
L.DomUtil.addClass(this._zoomOutButton, className);
}
if (this._disabled || map._zoom === map.getMaxZoom()) {
L.DomUtil.addClass(this._zoomInButton, className);
}
}
});
While not being explicit in the Leaflet class customization tutorial, there is a subtle distinction between factories, which are lowerCased and that you cannot extend, and Classes, which are PascalCased and on which you can use Leaflet extend mechanism:
var MyNewZoomControl = L.Control.Zoom.extend({
onAdd: function (map) {
// your new method content
}
}
That being said, if your new button does not really share functionality with the zoom buttons or is not "merged" with them, you could simply make a separate Control and insert it in the same corner position. There is also Leaflet EasyButton plugin which can help in this regard.
currently i'm starting with Ember, and i'm loving it! I'm with some difficulties, especially when it comes to components.
For you to understand, I'm going through old code to Ember, and I would like to turn this code into a Component, but I do not know actually how to start, since I do not know how to catch the button being clicked, and I also realized that Ember has several helpers, maybe I do not need any of this giant code to do what I want.
This is the old code result: http://codepen.io/anon/pen/WQjobV?editors=110
var eventObj = {};
var eventInstances = {};
var actual;
var others;
var clicked;
var createEventInstance = function (obj) {
for (var key in obj) {
eventInstances[key] = new Event(obj[key]);
}
};
var returnStyle = function (inCommon) {
var $inCommon = inCommon;
$inCommon.css({
width: '342.4px',
minWidth: '342.4px'
});
$inCommon.find('.cta').removeClass('hidden');
$inCommon.find('.event-close').removeClass('inline');
$inCommon.find('.event-info_list').removeClass('inline');
$inCommon.removeClass('hidden');
$inCommon.find('.expanded').slideUp();
$inCommon.find('.expanded').slideUp();
$inCommon.find('.event-arrow').remove();
$inCommon.find('h2').find('ul').remove('ul');
};
var Event = function (id) {
this.id = id;
};
Event.prototype.expandForm = function () {
actual.css('width', '100%');
actual.find('.event-info_list').addClass('inline');
actual.find('.expanded').slideDown().css('display', 'block');
actual.find('.event-close').addClass('inline');
};
Event.prototype.close = function () {
returnStyle(actual);
returnStyle(others);
};
Event.prototype.hideElements = function () {
clicked.addClass('hidden');
others.addClass('hidden');
};
Event.prototype.maskPhone = function () {
$('[name$=phone]').mask('(99) 99999-9999', {
placeholder: '(00) 0000-0000'
});
};
$('.submit-form').on('click', function (e) {
e.preventDefault();
var id = '.' + $(this).data('id');
var name = $(id).children('#person-name').val();
var email = $(id).children('#person-email').val();
var guests = $(id).children('#person-obs.guests').val();
var phone = $(id).children('#person-phone').val();
var participants = $(id).children('#booking-participants').val();
if (name === '' || email === '' || phone === '' || participants === '' || guests === '') {
alert('Preencha os campos obrigatórios.');
} else {
$(id).submit();
}
});
Event.prototype.createDropDown = function () {
actual.find('h2').addClass('event-change')
.append('<span class="event-arrow" aria-hidden="true">▼</span>')
.append(function () {
var self = $(this);
var list = '<ul class="dropdown hidden">';
$('.event').each(function (index) {
if ($(this).find('h2')[0] != self[0]) {
list += '<li data-index="' + index + '">' + $(this).find('h2').text() + '</li>';
}
});
return list;
}).click(function () {
if ($(this).attr('data-expanded') == true) {
$(this).find('ul').toggleClass('hidden');
$(this).attr('data-expanded', false);
} else {
$(this).find('ul').toggleClass('hidden');
$(this).attr('data-expanded', true);
}
}).find('li').click(function (e) {
e.stopPropagation();
actual.find('.event-info_list').removeClass('inline');
actual.find('h2').attr('data-expanded', false);
actual.find('h2').removeClass('event-change');
actual.find('.expanded').slideUp().css('display', 'inline-block');
others.removeClass('hidden');
actual.find('.cta').removeClass('hidden');
actual.find('h2').find('.event-arrow').remove();
actual.find('h2').off('click');
actual.find('h2').find('ul').remove('ul');
$($('.event')[$(this).attr('data-index')]).find('.cta').trigger('click');
});
};
Event.prototype.open = function () {
actual = $('[data-id="' + this.id + '"]');
others = $('.event').not(actual);
clicked = actual.find('.cta');
this.hideElements();
this.expandForm();
this.createDropDown();
this.maskPhone();
};
$('.event').each(function (i, event) {
var prop = 'id' + $(event).data('id');
var value = $(event).data('id');
eventObj[prop] = value;
});
createEventInstance(eventObj);
Basically i have this boxes, which box represent one booking in some event (will be populate by the server). When the user clicks in one box, this boxes expands and the other disappear. But than a dropbox will be created with the other boxes, so the user can navigate in the events by this dropdown.
I didn't do much with Ember, i transform the "events" div into a component with the name "BookingBoxComponent" and two actions:
SiteApp.BookingBoxComponent = Ember.Component.extend({
actions:
open: function() {
// HOW COULD I ACCESS THE CLICKED BUTTON HERE?
},
close: function() {
}
});
As you can see, i put two actions, one for opening the box and other for closing, should i just put the logic in both, or i can improve this like a Ember way?
I don't know if i am asking to much here, so if i am, at least i would like to know how to access the button clicked in the open method, i was trying passing as a parameter, like:
<button {{action 'open' this}}></button>
But didn't work.
I could offer 50 of my points to someone who help transform the old cold in a Ember way code.
Thanks.
The event object will be passed with every action as the last parameter, so when you specified this you were actually passing whatever object has context in that block. In your open function, do not pass this and do
open: function(event) {
// event.currentTarget would be the button
}
And now you can do something like event.currentTarget or event.target
I am attempting to implement toggling functionality into a program I am working on. Specifically, there are 3 possible scenarios when a user clicks a button.
Tool clicked while no other tool is currently active.
Tool clicked while another tool is currently active
Same tool is clicked to toggle it on/off
I am having trouble implementing this. Here is my code so far:
var toolState = {
img_draw_point: false,
img_draw_line: false,
img_draw_rectangle: false,
img_draw_ellipse: false,
img_draw_FreehandPolygon: false,
img_draw_FreehandPolyline: false,
img_draw_text: false,
img_draw_eraser: false,
};
var lastActiveTool;
on(dom.byId("div-tools-draw"), "click", function (evt) {
function disableActiveCSS() {
for (var property in toolState) {
$("img#" + property + ".k-button.single").removeClass("buttonSelected");
$("img#" + property + ".k-button.single").removeClass("buttonHoverState");
}
}
function enableCSS() {
$("img#" + evt.target.id + ".k-button.single").addClass("buttonSelected");
$("img#" + evt.target.id + ".k-button.single").addClass("buttonHoverState");
}
toolState[evt.target.id] = !toolState[evt.target.id];
if (toolState[evt.target.id] == toolState[lastActiveTool]) {
toolState[lastActiveTool] = false;
}
disableActiveCSS();
enableCSS();
if (evt.target.id == lastActiveTool) {
disableActiveCSS();
}
}
Any help would be greatly appreciated.
I see that your code contains the '$' notation so I used jQuery in my response. It also assumes that we only care if another tool is currently "ON". So the 3 options in my response are:
Turn on the selected tool if no tool is on.
Turn off the current tool and turn on the selected tool.
Turn off the current tool if it is currently on.
var lastActiveTool = false;
$.click("#div-tools-draw", function(evt) {
// Disable Active CSS
$("img.k-button.single").removeClass("buttonSelected").removeClass("buttonHoverState");
if (!lastActiveTool) {
activateTool(evt.target.id);
} else if (evt.target.id == lastActiveTool) {
sameToolToggle(evt.target.id);
} else {
otherToolToggle(evt.target.id);
}
};
var activateTool = function (id) {
$("img#" + id + ".k-button.single").addClass("buttonSelected")addClass("buttonHoverState");
lastActiveTool = evt.target.id;
};
var otherToolToggle = function(id) {
$("img#" + id + ".k-button.single").addClass("buttonSelected")addClass("buttonHoverState");
lastActiveTool = evt.target.id;
// Whatever else you need to do to toggle between tools
}
// Only gets called when the same tool is currently toggled ON
var sameToolToggle = function(id) {
lastActiveTool = false;
}
Looking off this example, notice how clicking on the Search button brings up a modal form with a darkened overlay behind it. Now notice how clicking on the Column Chooser button brings up a modal form but no overlay behind it.
My question is: how do I get the dark overlay to appear behind my Column Chooser popup?
There are currently undocumented option of the columnChooser:
$(this).jqGrid('columnChooser', {modal: true});
The demo demonstrate this. One can set default parameters for the columnChooser with respect of $.jgrid.col too:
$.extend(true, $.jgrid.col, {
modal: true
});
Recently I posted the suggestion to extend a little functionality of the columnChooser, but only a part of the changes are current code of the jqGrid. Nevertheless in the new version will be possible to set much more jQuery UI Dialog options with respect of new dialog_opts option. For example the usage of the following will be possible
$(this).jqGrid('columnChooser', {
dialog_opts: {
modal: true,
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
To use full features which I suggested you can just overwrite the standard implementation of columnChooser. One can do this by including the following code
$.jgrid.extend({
columnChooser : function(opts) {
var self = this;
if($("#colchooser_"+$.jgrid.jqID(self[0].p.id)).length ) { return; }
var selector = $('<div id="colchooser_'+self[0].p.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>');
var select = $('select', selector);
function insert(perm,i,v) {
if(i>=0){
var a = perm.slice();
var b = a.splice(i,Math.max(perm.length-i,i));
if(i>perm.length) { i = perm.length; }
a[i] = v;
return a.concat(b);
}
}
opts = $.extend({
"width" : 420,
"height" : 240,
"classname" : null,
"done" : function(perm) { if (perm) { self.jqGrid("remapColumns", perm, true); } },
/* msel is either the name of a ui widget class that
extends a multiselect, or a function that supports
creating a multiselect object (with no argument,
or when passed an object), and destroying it (when
passed the string "destroy"). */
"msel" : "multiselect",
/* "msel_opts" : {}, */
/* dlog is either the name of a ui widget class that
behaves in a dialog-like way, or a function, that
supports creating a dialog (when passed dlog_opts)
or destroying a dialog (when passed the string
"destroy")
*/
"dlog" : "dialog",
/* dlog_opts is either an option object to be passed
to "dlog", or (more likely) a function that creates
the options object.
The default produces a suitable options object for
ui.dialog */
"dlog_opts" : function(opts) {
var buttons = {};
buttons[opts.bSubmit] = function() {
opts.apply_perm();
opts.cleanup(false);
};
buttons[opts.bCancel] = function() {
opts.cleanup(true);
};
return $.extend(true, {
"buttons": buttons,
"close": function() {
opts.cleanup(true);
},
"modal" : opts.modal ? opts.modal : false,
"resizable": opts.resizable ? opts.resizable : true,
"width": opts.width+20,
resize: function (e, ui) {
var $container = $(this).find('>div>div.ui-multiselect'),
containerWidth = $container.width(),
containerHeight = $container.height(),
$selectedContainer = $container.find('>div.selected'),
$availableContainer = $container.find('>div.available'),
$selectedActions = $selectedContainer.find('>div.actions'),
$availableActions = $availableContainer.find('>div.actions'),
$selectedList = $selectedContainer.find('>ul.connected-list'),
$availableList = $availableContainer.find('>ul.connected-list'),
dividerLocation = opts.msel_opts.dividerLocation || $.ui.multiselect.defaults.dividerLocation;
$container.width(containerWidth); // to fix width like 398.96px
$availableContainer.width(Math.floor(containerWidth*(1-dividerLocation)));
$selectedContainer.width(containerWidth - $availableContainer.outerWidth() - ($.browser.webkit ? 1: 0));
$availableContainer.height(containerHeight);
$selectedContainer.height(containerHeight);
$selectedList.height(Math.max(containerHeight-$selectedActions.outerHeight()-1,1));
$availableList.height(Math.max(containerHeight-$availableActions.outerHeight()-1,1));
}
}, opts.dialog_opts || {});
},
/* Function to get the permutation array, and pass it to the
"done" function */
"apply_perm" : function() {
$('option',select).each(function(i) {
if (this.selected) {
self.jqGrid("showCol", colModel[this.value].name);
} else {
self.jqGrid("hideCol", colModel[this.value].name);
}
});
var perm = [];
//fixedCols.slice(0);
$('option:selected',select).each(function() { perm.push(parseInt(this.value,10)); });
$.each(perm, function() { delete colMap[colModel[parseInt(this,10)].name]; });
$.each(colMap, function() {
var ti = parseInt(this,10);
perm = insert(perm,ti,ti);
});
if (opts.done) {
opts.done.call(self, perm);
}
},
/* Function to cleanup the dialog, and select. Also calls the
done function with no permutation (to indicate that the
columnChooser was aborted */
"cleanup" : function(calldone) {
call(opts.dlog, selector, 'destroy');
call(opts.msel, select, 'destroy');
selector.remove();
if (calldone && opts.done) {
opts.done.call(self);
}
},
"msel_opts" : {}
}, $.jgrid.col, opts || {});
if($.ui) {
if ($.ui.multiselect ) {
if(opts.msel == "multiselect") {
if(!$.jgrid._multiselect) {
// should be in language file
alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");
return;
}
opts.msel_opts = $.extend($.ui.multiselect.defaults,opts.msel_opts);
}
}
}
if (opts.caption) {
selector.attr("title", opts.caption);
}
if (opts.classname) {
selector.addClass(opts.classname);
select.addClass(opts.classname);
}
if (opts.width) {
$(">div",selector).css({"width": opts.width,"margin":"0 auto"});
select.css("width", opts.width);
}
if (opts.height) {
$(">div",selector).css("height", opts.height);
select.css("height", opts.height - 10);
}
var colModel = self.jqGrid("getGridParam", "colModel");
var colNames = self.jqGrid("getGridParam", "colNames");
var colMap = {}, fixedCols = [];
select.empty();
$.each(colModel, function(i) {
colMap[this.name] = i;
if (this.hidedlg) {
if (!this.hidden) {
fixedCols.push(i);
}
return;
}
select.append("<option value='"+i+"' "+
(this.hidden?"":"selected='selected'")+">"+colNames[i]+"</option>");
});
function call(fn, obj) {
if (!fn) { return; }
if (typeof fn == 'string') {
if ($.fn[fn]) {
$.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
}
} else if ($.isFunction(fn)) {
fn.apply(obj, $.makeArray(arguments).slice(2));
}
}
var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
call(opts.dlog, selector, dopts);
var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
call(opts.msel, select, mopts);
// fix height of elements of the multiselect widget
var resizeSel = "#colchooser_"+$.jgrid.jqID(self[0].p.id),
$container = $(resizeSel + '>div>div.ui-multiselect'),
$selectedContainer = $(resizeSel + '>div>div.ui-multiselect>div.selected'),
$availableContainer = $(resizeSel + '>div>div.ui-multiselect>div.available'),
containerHeight,
$selectedActions = $selectedContainer.find('>div.actions'),
$availableActions = $availableContainer.find('>div.actions'),
$selectedList = $selectedContainer.find('>ul.connected-list'),
$availableList = $availableContainer.find('>ul.connected-list');
$container.height($container.parent().height()); // increase the container height
containerHeight = $container.height();
$selectedContainer.height(containerHeight);
$availableContainer.height(containerHeight);
$selectedList.height(Math.max(containerHeight-$selectedActions.outerHeight()-1,1));
$availableList.height(Math.max(containerHeight-$availableActions.outerHeight()-1,1));
// extend the list of components which will be also-resized
selector.data('dialog').uiDialog.resizable("option", "alsoResize",
resizeSel + ',' + resizeSel +'>div' + ',' + resizeSel + '>div>div.ui-multiselect');
}
});
In the case you can continue to use the original minimized version of jquery.jqGrid.min.js and the code which use can be just $(this).jqGrid('columnChooser');. Together with all default settings it will be like
$.extend(true, $.ui.multiselect, {
locale: {
addAll: 'Make all visible',
removeAll: 'Hidde All',
itemsCount: 'Avlialble Columns'
}
});
$.extend(true, $.jgrid.col, {
width: 450,
modal: true,
msel_opts: {dividerLocation: 0.5},
dialog_opts: {
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
onClickButton: function () {
$(this).jqGrid('columnChooser');
}
});
The demo demonstrate the approach. The main advantage of the changes - the really resizable Column Chooser:
UPDATED: Free jqGrid fork of jqGrid, which I develop starting with the end of 2014, contains of cause the modified code of columnChooser.
I get the following error while trying the code on the mobile device.
Result of expression 'selector.data('dialog').uiDialog' [undefined] is not an object.
The error points to the following line of code.
selector.data('dialog').uiDialog.resizable("option", "alsoResize", resizeSel + ',' + resizeSel +'>div' + ',' + resizeSel + '>div>div.ui-multiselect');
When I inspect the code, I find that the data object does not have anything called uiDialog.
just been looking thru the code, try adding this line:
jqModal : true,
to this code:
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
onClickButton: function () {
....
like this:
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
jqModal : true,
onClickButton: function () {
....