Script doesn't work if misplaced in jQuery - javascript

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?

Related

How to display vtype warning and don't set field invalid?

This code doesn't work for me because I can't do anything with form.isValid(), so I only need to show the tooltip and color textfield border to show user that I don't recommend to use length > 15, but if code does it anyway, its ok.
// I have some field
{
xtype: 'textfield',
maskRe: /[0-9.]/,
vtype: 'imei',
fieldLabel: 'IMEI:',
name: 'imei',
flex: 1
}
// validation for textfield on keypress
imei: function (v) {
return v.length < 16;
},
imeiText: 'length more then 15 symbols is not recommended'
// validation on save button click
validateForm: function (form) {
if (!form.isValid()) {
// don't save form
}// can't save form because imei is not valid
}
Is there any method to display vtype tooltip, color border and do not set textfield invalid ?
any help in this regards will be appreciated.
you can use listener in your textfield:
listeners: {
change: function (c, newValue, oldValue) {
var tn = newValue.replace(/[^0-9]/g, '');
if (tn.length === 0) {
setTimeout(function () {
c.markInvalid('Imei length must be at least 1 symbol');
}, 100);
}
if (tn.length > 15) {
setTimeout(function () {
c.markInvalid('Imei length more than 15 symbols is not recommended');
}, 100);
}
}
},
There is a timeout, because base field trigger the markInvalid as '' after pushing event.
Look at example on fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2r9h

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>

Kendo Menu selection issue

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";
}
}
}
});

Popover not hiding when leaving the textbox in Opera 12

I'm using the following script to display popovers on focus with HTML support in Bootstrap 3:
$(document).ready(function () {
$(".focus-popover").each(function (index) {
var showPopover = function () {
$(this).popover('show');
};
var hidePopover = function () {
$(this).popover('hide');
};
$(this).popover({
html: true,
placement: $(this).attr('data-placement'),
trigger: 'manual'
})
.focus(showPopover)
.blur(hidePopover);
})
});
However this input ...
<input type="date" ID="test2" class="form-control focus-popover" data-original-title="This is my title" data-placement="top" data-container="body" data-content="Click away and see how this will be dismissed.<br />However, on Opera 12 it will remain."></input>
... is somehow bugged in Opera 12. Due the fact the input type is "date" and not "text" it will not hide the popover when leaving the textbox.
Please look at this Example in Opera 12 as well as any other browser.
What can I do to make it work properly?
Apparently the date-picker prevents the browser from triggering the blur event once it lost focus by clicking away.
It does triggers the blur event only if you keep tabbing to lost focus or by changing the values by picking a date.
So, basically a workaround could be emulating the blur event by using the click/focus of another element.
Workaround
$(document).ready(function () {
$(".focus-popover").each(function (index) {
var showPopover = function () {
$(this).popover('show');
};
var hidePopover = function () {
$(this).popover('hide');
};
$(this).popover({
html: true,
placement: $(this).attr('data-placement'),
trigger: 'manual'
})
.focus(showPopover)
.blur(hidePopover);
})
// The nasty Opera < 12 "workaround"
if ( window.opera && +window.opera.version() <= 13 ) {
var $buggyInput = $("#test2"), // Caching is important!
buggyInputFocus = false,
buggyFocus = function(event) {
event.stopPropagation();
if(!buggyInputFocus) {
$(this).popover('show');
buggyInputFocus = true;
}
},
buggyBlur = function(event) {
$(this).popover('hide');
buggyInputFocus = false;
}
;
// The focus also stop triggering if it was blurred then clicked back, so we added a click. It doesn't run buggyFocus twice since it only execute itself if it hasn't been focused first
$buggyInput.on({
"focus": buggyFocus,
"click": buggyFocus,
"blur":buggyBlur,
"change":buggyBlur // On change is also important, you don't want to leave it open when it changes
})
// Since it doesn't the blur event, we fake it by capturing focus or click on the html tag
$("html").on({
click: function() {
if ( buggyInputFocus ) $buggyInput.trigger("blur");
},
focus: function() {
if ( buggyInputFocus ) $buggyInput.trigger("blur");
}
})
}
});
Fiddle: http://jsfiddle.net/5wsq38u3/4/
EDIT: For more than 1 date input
$(document).ready(function () {
$(".focus-popover").each(function (index) {
var showPopover = function () {
$(this).popover('show');
};
var hidePopover = function () {
$(this).popover('hide');
};
$(this).popover({
html: true,
placement: $(this).attr('data-placement'),
trigger: 'manual'
})
.focus(showPopover)
.blur(hidePopover);
})
// The nasty Opera < 12 "workaround"
if (window.opera && +window.opera.version() < 13) {
var $buggyInputs = $(".operaFix"), // Caching is important!
buggyInputFocus = false,
buggyInput = {}, // We store an instance of the focused element
buggyFocus = function(event) {
event.stopPropagation();
if(!buggyInputFocus) {
$(buggyInput).popover('hide');
$(this).popover('show');
buggyInputFocus = true;
buggyInput = $(this);
}
else if ($(buggyInput).attr("id") !== $(this).attr("id")){
$(buggyInput).trigger("blur")
}
},
buggyBlur = function(event) {
$(this).popover('hide');
buggyInputFocus = false;
buggyInput = {}
}
;
// The focus also stop triggering if it was blurred then clicked back, so we added a click. It doesn't run buggyFocus twice since it only execute itself if it hasn't been focused first
$buggyInputs.on({
"focus": buggyFocus,
"click": buggyFocus,
"blur": buggyBlur,
"change": buggyBlur // On change is also important, you don't want to leave it open when it changes
})
// Since it doesn't the blur event, we fake it by capturing focus or click on the html tag
$("html").on({
click: function() {
if (buggyInputFocus) $(buggyInput).trigger("blur");
},
focus: function() {
if (buggyInputFocus) $(buggyInput).trigger("blur");
}
})
}
});
JSBin: http://jsbin.com/xucagomutera/1/edit

Catch Ctrl+Enter when the user types text in Ext.form.field.HtmlEditor

I'm trying to make an Ajax request when the user presses Ctrl + Enter while entering text in Ext.form.field.HtmlEditor (xtype:'htmleditor'), but I don't know how to do it.
I got a button next to the 'htmleditor' which can send the value of the 'htmleditor', but I'd like to add a keyboard shortcut for that operation with Ctrl + Enter.
It need to be made with Ext JS 4 - somehow I must add something like 'keypress' listener to my htmleditor object...
Here is the code...
this.htmleditor = this.addComment.add({
region: 'center',
xtype: 'htmleditor',
margin: '0 0 0 0',
enableSourceEdit: false,
height: 200
});
You cannot listen for events in the default htmleditor. So you need use an updated version of it.
This code can help you (it is for Ext JS 3, so maybe you need change it for version 4):
Cyber.ui.HtmlEditor = Ext.extend(Ext.form.HtmlEditor, {
frame : true,
initComponent : function() {
Cyber.ui.HtmlEditor.superclass.initComponent.call(this);
this.addEvents('submit');
},
initEditor : function() {
Cyber.ui.HtmlEditor.superclass.initEditor.call(this);
if (Ext.isGecko) {
Ext.EventManager.on(this.doc, 'keypress', this.fireSubmit,
this);
}
if (Ext.isIE || Ext.isWebKit || Ext.isOpera) {
Ext.EventManager.on(this.doc, 'keydown', this.fireSubmit,
this);
}
},
fireSubmit : function(e) {
if (e.ctrlKey && Ext.EventObject.ENTER == e.getKey()) {
// Do what you need here
}
}
});
Ext.reg('customeditor', Cyber.ui.HtmlEditor);
And in your form:
this.htmleditor = this.addComment.add({
region: 'center',
xtype: 'customeditor',
margin: '0 0 0 0',
enableSourceEdit: false,
height: 200
});
I played a lot with Ext JS 4 and found the way (you need just include this code before you'll use htmleditor):
Ext.form.HtmlEditor.override({
frame : true,
initComponent: function() {
this.callOverridden();
this.addEvents('submit');
},
initEditor : function() {
this.callOverridden();
var me = this;
var doc = me.getDoc();
if (Ext.isGecko) {
Ext.EventManager.on(doc, 'keypress', me.fireSubmit, me);
}
if (Ext.isIE || Ext.isWebKit || Ext.isOpera) {
Ext.EventManager.on(doc, 'keydown', me.fireSubmit, me);
}
},
fireSubmit : function(e) {
if (e.ctrlKey && Ext.EventObject.ENTER == e.getKey()) {
// Do what you need here
alert('yes!');
}
}
});
This may be what you're after (was already on Stack Overflow): Ctrl + Enter using jQuery in a TEXTAREA:
$('#textareaId').keydown(function (e) {
e = e || event; // For compatibility with Internet Explorer (I believe)
if (e.ctrlKey && e.keyCode == 13) {
// Ctrl + Enter pressed
}
});
This worked for Ext JS 6 (the example disables the Enter key):
Ext.create('Ext.form.HtmlEditor', {
width: 580,
height: 250,
renderTo: Ext.getBody(),
listeners:{
initialize: function(editor){
const doc = editor.getDoc();
const docEl = Ext.get(doc);
docEl.on({
keypress: (e)=>{
if (e.event.code === 'Enter'){
e.preventDefault();
}
},
delegated:false,
scope: editor
});
}
}
});

Categories

Resources