Kendo Menu selection issue - javascript

I've a kendo menu to dynamically enable or disable the kendo grid columns. When I select the options from the KendoMenu, the selection is firing twice. I've created the demo version below.
demo
$("#menu").kendoMenu({
dataSource: [{
text: "Menu",
items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
var selector;
$.each(grid.columns, function () {
if (this.hidden) {
selector = "input[data-field='" + this.field + "']";
$(selector).prop("checked", false);
}
});
},
select: function (e) {
// don't show/hide for menu button --- calling twice
if ($(e.item).parent().filter("div").length) return;
console.log("******");
var input = $(e.item).find("input.check");
var field = $(input).data("field");
if ($(input).is(":checked")) {
grid.showColumn(field);
} else {
grid.hideColumn(field);
}
}});
Check the console log while selecting the menu items.

Adding the checkbox to the menu item seems to lead to kendo firing the event for the menu click and the checkbox check. It seems hard to differentiate between the two instances, so it might be better to do something different to indicate the check. The following icons can be used - maybe use the tick icon instead of an actual checkbox:
http://demos.telerik.com/kendo-ui/styling/icons

I've fixed the issue with the updated code
$("#menu").kendoMenu({
dataSource: [{
text: "Menu",
items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
var selector;
$.each(grid.columns, function () {
if (this.hidden) {
selector = "input[data-field='" + this.field + "']";
$(selector).prop("checked", false);
}
});
},
select: function (e) {
// don't show/hide for menu button
if ($(e.item).parent().filter("div").length) return;
var removeItemFlag = false;
var input = $(e.item).find("label");
var selectedValue = input[0].innerHTML;
if(selectedValue)
{
for(var i=0; i< droplist.length; i++){
if(droplist[i] === selectedValue){
removeItemFlag = true
input[0].classList.remove = "fa fa-check-square-o";
input[0].className = "fa fa-square-o";
break;
}
}
var selectedIndex = droplist.indexOf(selectedValue);
if (selectedIndex > -1 && removeItemFlag) {
droplist.splice(selectedIndex, 1);
grid.hideColumn(selectedValue);
}else{
droplist.push(selectedValue);
grid.showColumn(selectedValue);
input[0].className = "fa fa-check-square-o";
}
}
}
});

Related

Script doesn't work if misplaced in jQuery

i will create website with validate in input field, i used Mottie Keyboard in every input field, and i use validation on it. i will create disable button when validation is not correct. And I get a script for it, directly from github page mottie keyboard. I want is if the validation was not correct then the button in a virtual keyboard can not be pressed. Here's the script:
var toggleKeysIfEmpty = function( kb ) {
var toggle = kb.$preview.val() === '';
console.log( toggle, kb.$preview.val() );
kb.$keyboard
.find('.ui-keyboard-bksp')
.toggleClass('disabled', toggle)
.prop('disabled', toggle);
};
And this my script before adding script above:
$(function() {
// change default navigation keys
$('#jkeyboard2, #jkeyboard').keyboard({
layout: 'num',
// setting alwaysOpen does odd things with input focus on initialization
// best to leave it false and focus on the desired input
// alwaysOpen: true,
autoAccept: true,
usePreview: false,
position: {
of: $(window),
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
my: 'center bottom',
at: 'center bottom',
at2: 'center bottom'
},
maxLength: 4,
layout: 'custom',
customLayout: {
'normal': ['1 2 3', '4 5 6', '7 8 9', '0 . {b}'],
},
visible : function(e, keyboard) {
toggleKeysIfEmpty( keyboard );
},
tabNavigation: true,
initialFocus: false,
initialized: function() {
setTimeout(function(){
$('#jkeyboard').focus();
}, 200);
},
change: function(e, keyboard, el) {
if (keyboard.$el.val().length >= 4) {
// switchInput( goToNext, isAccepted );
keyboard.switchInput(true, true);
} else if (keyboard.$el.val() === "" && keyboard.last.key === "bksp") {
// go to previous if user hits backspace on an empty input
keyboard.switchInput(false, true);
}
}
})
});
$(document).ready(function() {
$('#jkeyboard').bind('keyboardChange', function (e, keyboard, el) {
if (validatePhone('jkeyboard')) {
$('#spnPhoneStatus').html('');
$('#spnPhoneStatus').css('color', 'green');
} else {
$('#spnPhoneStatus').html('<b>Wrong Number</b>');
$('#spnPhoneStatus').css('color', 'red');
}
});
});
function validatePhone(jkeyboard) {
var a = document.getElementById(jkeyboard).value;
var filter = /^0(?:8(?:(?:1(?:[789][0-9]{0,9})?|3(?:[1238][0-9]{0,9})?|5(?:9[0-9]{0,9})?|7(?:[78][0-9]{0,9})?)?)?)?$/;
//var filter = /^0([8]([1357]([123789]([0-9]{0,8}))?)?)?$/;
if (filter.test(a)) {
return true;
} else {
return false;
}
}
I want disable backspace button if validation was not correct, so i added the script. And become like this:
$(function() {
// change default navigation keys
$('#jkeyboard2, #jkeyboard').keyboard({
layout: 'num',
// setting alwaysOpen does odd things with input focus on initialization
// best to leave it false and focus on the desired input
// alwaysOpen: true,
autoAccept: true,
usePreview: false,
position: {
of: $(window),
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
my: 'center bottom',
at: 'center bottom',
at2: 'center bottom'
},
maxLength: 4,
layout: 'custom',
customLayout: {
'normal': ['1 2 3', '4 5 6', '7 8 9', '0 . {b}'],
},
visible : function(e, keyboard) {
toggleKeysIfEmpty( keyboard );
},
tabNavigation: true,
initialFocus: false,
initialized: function() {
setTimeout(function(){
$('#jkeyboard').focus();
}, 200);
},
change: function(e, keyboard, el) {
if (keyboard.$el.val().length >= 4) {
// switchInput( goToNext, isAccepted );
keyboard.switchInput(true, true);
} else if (keyboard.$el.val() === "" && keyboard.last.key === "bksp") {
// go to previous if user hits backspace on an empty input
keyboard.switchInput(false, true);
}
}
})
});
$(document).ready(function() {
$('#jkeyboard').bind('keyboardChange', function (e, keyboard, el) {
if (validatePhone('jkeyboard')) {
$('#spnPhoneStatus').html('');
$('#spnPhoneStatus').css('color', 'green');
} else {
$('#spnPhoneStatus').html('<b>Wrong Number</b>');
$('#spnPhoneStatus').css('color', 'red');
var toggleKeysIfEmpty = function( kb ) {
var toggle = kb.$preview.val() === '';
console.log( toggle, kb.$preview.val() );
kb.$keyboard
.find('.ui-keyboard-bksp')
.toggleClass('disabled', toggle)
.prop('disabled', toggle);
};
}
});
});
function validatePhone(jkeyboard) {
var a = document.getElementById(jkeyboard).value;
var filter = /^0(?:8(?:(?:1(?:[789][0-9]{0,9})?|3(?:[1238][0-9]{0,9})?|5(?:9[0-9]{0,9})?|7(?:[78][0-9]{0,9})?)?)?)?$/;
//var filter = /^0([8]([1357]([123789]([0-9]{0,8}))?)?)?$/;
if (filter.test(a)) {
return true;
} else {
return false;
}
}
it's doesn't work, and i try put the code i get at the top of my code. it's work but backspace button can not be pressed from the start. Anyone can fix it?
Here's my fiddle: DEMO
I have changed your code to update the fiddle here : you wanted to
disable backspace button if validation was not correct
so here's what I did:
I renamed toggleKeysIfEmpty to toggleBackspaceKey and changed its implementation to add the CSS classes to render the button correctly depending on the desired state:
var toggleBackspaceKey = function( kb, toggle ) {
console.log( toggle, kb.$preview.val() );
var $bkSpaceBtn = kb.$keyboard.find('.ui-keyboard-bksp');
if (toggle) {
$bkSpaceBtn
.attr({
'disabled': 'disabled',
'aria-disabled': 'true'
})
.removeClass(kb.options.css.buttonHover)
.addClass(kb.options.css.buttonDisabled);
} else {
$bkSpaceBtn
.removeAttr('disabled')
.attr({
'aria-disabled': 'false'
})
.addClass(kb.options.css.buttonDefault)
.removeClass(kb.options.css.buttonDisabled);
}
};
I changed the implementation of the bksp keyaction handler to ensure that if it's invoked when the button is disabled, no action is executed. The handler for the backspace will be invoked if you press the corresponding key or if you double click on the backspace button in the keyboard even when it's disabled (this might be a bug). Here is the handler code: if the backspace button is enabled it simply invokes the default backspace processing handler. Also, this function is invoked once from the visible callback:
var processBkSpcKey = function(kb) {
var originalBkSpaceHandler = $.keyboard.keyaction.bksp;
$.keyboard.keyaction.bksp = function(base) {
// If the backspace button is disabled, do not process it.
var $bkSpaceBtn = kb.$keyboard.find('.ui-keyboard-bksp');
if($bkSpaceBtn.hasClass(kb.options.css.buttonDisabled)) {
return false;
}
return originalBkSpaceHandler.apply(kb, arguments);
}
};
With these changes in place, the backspace button is disabled if the input is empty or if the validation fails, in this case though, how would the user clear the contents of the input?

Issue swith jquery multiselect plugin

I am using jquery multiselct plug-in https://plugins.jquery.com/multi-select/
In one scenario I need to select some default values and then disable them so no one can remove them.Below is my code where i have made some options selected based on some condition.
$('#members_select3').find('option').remove().end()
$.each(response.results, function (i, item) {
$('#members_select3').append($('<option>', {
selected: function(){
if (**condition comes here**){
return true;
},
value: item.uid,
text : item.contact,
}));
});
enable_multi_select_search('members_select3');
Now as per docs if i use disable option in above code the option becomes disable but it is not selected any-more means the option is available for selection rather then default selected.
$('#members_select3').find('option').remove().end()
$.each(response.results, function (i, item) {
$('#members_select3').append($('<option>', {
selected: function(){
if (**condition comes here**){
return true;
}
},
value: item.uid,
text : item.contact,
disabled: function(){
if (**condition comes here**){
return true;
}
}
}));
});
enable_multi_select_search('members_select3');
Default function of plug-in n
function enable_multi_select_search(id_){
// refresh previous multi select box
$('#members_select3').multiSelect("destroy");
// create new
$('#'+id_).multiSelect({
selectableHeader: "<input type='text' class='form-control search-input' autocomplete='off' placeholder='search...'>",
selectionHeader: "<input type='text' class='form-control search-input' autocomplete='off' placeholder='search...'>",
afterInit: function (ms) {
var that = this,
$selectableSearch = that.$selectableUl.prev(),
$selectionSearch = that.$selectionUl.prev(),
selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)',
selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected';
that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
.on('keydown', function (e) {
if (e.which === 40) {
that.$selectableUl.focus();
return false;
}
});
that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
.on('keydown', function (e) {
if (e.which == 40) {
that.$selectionUl.focus();
return false;
}
});
},
afterSelect: function () {
this.qs1.cache();
this.qs2.cache();
},
afterDeselect: function () {
this.qs1.cache();
this.qs2.cache();
}
});
}
you should distinguish between disabled and readOnly:
disabled: the option is not selectable, even not as a default
readOnly: the state of the option (selected or not) can not be changed
I guess, you're heading for the second one.
EDIT:
Maybe you can change the plugin like this (not tested):
$('#members_select3').append($('<option>', {
selected: function(){
if (**condition comes here**){
return true;
}
},
value: item.uid,
text : item.contact,
disabled: false,
readOnly: function(){
if (**condition comes here**){
return true;
}
}
}));
});

Enter click does not trigger JQuery dialog open

Me and a few co-workers are slightly puzzled by this issue. We have an onclick event in Javascript which opens a JQuery dialog box. This works when you actually click the designated button. However, when you press enter, it will trigger the onclick event and also perform the other required functions. But when it hits the dialog, it does not open. Strangely, if you insert an alert before the dialog code, it will open the alert and then open the dialog. Any fixes?
JQuery:
$(document).ready(function () {
$('#applyFilter').click(function () {
console.log('event triggered');
var suppString = $('#FK_SupplierID').val();
var carryOn = true;
//if the supplier ID fields is showing and populated:
//check if supplier ID values are all numeric, if not show message and modal form
if (suppString != null) {
suppString.split(",").forEach(function (item) {
if (item != '') {
if (!isInt(item)) {
//invalid value - set carryOn to false and exit the loop
carryOn = false;
return false;
}
}
});
if (!carryOn) {
alert("The Supplier ID field must only have a whole number, or a comma-separated list of whole numbers. Please type in a valid value or click the ellipsis button to select the required suppliers from the supplier list.")
return false;
} else {
//check if supplier label is populated - if not, populate it
if (suppString != '' && $('#suppliersShown').text() == '') {
//GetSupplierNames
$.getJSON("./GetSupplierNames", { ids: suppString },
function (data) {
$('#suppliersShown').text("Supplier(s):" + data);
$('#suppliersShown').show();
}
);
}
}
}
$('#dialog-processing').dialog({
closeOnEscape: false,
//open: function (event, ui) {
// $(".ui-dialog-titlebar-close").hide();
//},
autoOpen: false,
width: 400,
resizable: false,
modal: true
});
$('#dialog-processing').dialog('open');
var table = $('#invoiceTable').on('processing.dt', function (e, settings, processing) {
// $('#dialog-processing').dialog('close');
}
).DataTable({
retrieve: true,
});
table.ajax.url('./FilterData/?filterString=' + FilterParams()).load(function (json) { console.log(json); });
});
});able({
retrieve: true,
});
table.ajax.url('./FilterData/?filterString=' + FilterParams()).load(function (json) { console.log(json); });
});
HTML:
<button id="applyFilter">click</button>

Select all - Select none in Ext JS Combobox

Based on the answer to this question: Select all in ExtJS 4.0 Combobox
afterrender: function () {
me.container.on({
click: function(e) {
console.log('on clic called');
var el = e.getTarget('div', 3, true);
if(el.getAttribute('action') == 'select-all') {
me.select(me.getStore().getRange());
me.setSelectedCount(me.getStore().getRange().length, flabel);
allSelected = true;
} else if (el.getAttribute('action') == 'select-none'){
me.reset();
allSelected = false;
}
}
})
}
I have implemented my own Combobox with 'Select All' and 'Select None' in Ext JS.
However, if I use it more than once, the actions are applied to all the instances. Just try to click 'Select all / Select none' in one combo and you will see how the other changes: http://jsfiddle.net/hernan666/vfbkgmmu/.
For the original answer I get the same wrong behavior: http://jsfiddle.net/hernan666/dFEsc/414/
I would appreciate any help to fix this issue
I think using me.container.on is the problem.
I tried a different approach, based on your example, listening to the expand and then to the picker element click and it seems to work:
listeners: {
expand: {
single: true,
fn: function () {
var me = this,
flabel = this.getFieldLabel();
me.picker.on({
click: {
element: 'el',
fn: function (e) {
var el = e.getTarget('div', 3, true);
if (el.getAttribute('action') == 'select-all') {
me.select(me.getStore().getRange());
me.setSelectedCount(me.getStore().getRange().length, flabel);
allSelected = true;
} else if (el.getAttribute('action') == 'select-none') {
me.reset();
allSelected = false;
}
}
}
});
}
}
}
A working example: http://jsfiddle.net/ot0eaqv1/

jQuery contextMenu disable items based on div content

I've been going trough documents of this plugin and it looked promising, but at the end I wasn't able to find out that what I was looking for.
http://medialize.github.com/jQuery-contextMenu/docs.html
Here is what I wanted trough example, this is example of context menu items
$.contextMenu({
selector: '.context-menu-one',
callback: function(key, options) {
var m = "clicked: " + key;
window.console && console.log(m) || alert(m);
},
items: {
"item1": {name: "Clickable", icon: "edit"},
"item2": {
name: "Disabled",
icon: "cut",
disabled: function(key, opt) {
// this references the trigger element
return !this.data('cutDisabled');
}
}
}
});
. If my div (context-menu-one) has some content inside like <span class="test">x</span> disable or enable menu based on that.
So in the case above if my div(context-menu-one) has span with class test that has textvalue x disable menu item2
How would one do that? doesn't have to be code, leading me to good direction = good code if possible at all
Edit:
Here is jsfiddle example :
http://jsfiddle.net/XZEUN/2/
So because first context-menu-one has span with class x the item2 should be disabled, but not for other one
you need to define your own events like in this fiddle
html
<div class="context-menu-one box menu-1">
<strong>right click me</strong>
<span data-item="edit"></span>
</div>​
javascript
events: {
show: function(opt) {
var m = opt.$menu;
$(this).find('span[data-item]').each(function(i, e) { //<-- this search for all span with data-item attribute
var p = $(e).data('item') + 'Disabled'; //<-- here i compose editDisabled
if (m.data(p) === true) m.data(p, 1); //<-- this is for mantain previuos disabling
else m.data(p, true);
});
m = null; //<-- this for breaking possible circular references/memory leaks
},
hide: function(opt) {
var m = opt.$menu;
$(this).find('span[data-item]').each(function(i, e) {
var p = $(e).data('item') + 'Disabled';
if (m.data(p) === 1) m.data(p, true); //<-- this reset the previuos disabling
else m.removeData(p);
});
m = null;
}
}
If you want to disable a context menu binded to an specific selector you can do something like this:
$.contextMenu( 'destroy', '.context-menu-one' );
See example here:
http://jsfiddle.net/ATyjn/

Categories

Resources