Check capslock is on or off on button click - javascript

I have a application in which there is one textbox and a button.I want the application to behave in such a way that when a user types some text in the text box,and after that when the user click the button,it should show whether the capslock is on or off

Take a look at this previous question: How do you tell if caps lock is on using JavaScript? has some great scripts/responses there for you.

In jQuery,
$('#example').keypress(function(e) {
var s = String.fromCharCode( e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
alert('caps is on');
}
});
Avoid the mistake, like the backspace key, s.toLowerCase() !== s is needed.
You have try this code?
function isCapslock(e){
e = (e) ? e : window.event;
var charCode = false;
if (e.which) {
charCode = e.which;
} else if (e.keyCode) {
charCode = e.keyCode;
}
var shifton = false;
if (e.shiftKey) {
shifton = e.shiftKey;
} else if (e.modifiers) {
shifton = !!(e.modifiers & 4);
}
if (charCode >= 97 && charCode <= 122 && shifton) {
return true;
}
if (charCode >= 65 && charCode <= 90 && !shifton) {
return true;
}
return false;
}

You could use the capslockstate jQuery plugin.
When the button is clicked you could then call $(window).capslockstate("state"); and that would tell you the state of the Caps Lock key.
Note that the state of the Caps Lock key doesn't have to be the same as when they type the text and when they click the button.

Related

How to catch Drag and Drop event in JQuery?

On a textbox; there is decimal validation:
i.e User can enter only Numbers(upto two place decimal) and Dot.
Those are on keypress and keyup.
When number is entered directly, it works.
But when we drag and drop some alphabets in textbox
then it does not work; till i click in textbox
What events are provided by Javascript which help me to detect whether values is dragged and dropped to textbox.
Try this:
$(document).ready(function() {
var oldVal = '';
$('.myTexbox').keypress(function (event) {
var a = isDecimalNumber(event, this)
if (this.value.match("^[0-9]*[.,]?[0-9]{0,2}$"))
oldVal = this.value;
return a;
});
$('.myTexbox').keyup(function (event) {
if (!this.value.match("^[0-9]*[.,]?[0-9]{0,2}$")) {
$(this).val(oldVal);
}
});
$('.myTexbox').on("drop", function(event) {
event.preventDefault();
event.stopPropagation();
if (!this.value.match("^[0-9]*[.,]?[0-9]{0,2}$")) {
$(this).val(oldVal);
}
});
});
function isDecimalNumber(eve, element) {
var charCode = (eve.which) ? eve.which : event.keyCode
if (charCode == 44 || charCode == 46 || charCode == 8 || (charCode > 48 && charCode < 57))
return true;
return false;
}
I think this is exactly what you need.
I tested the code in JS Fiddle and it works like expected.

How to allow only numbers in a texbox but also allow entry with French keyboard

I have the following code to allow only numbers to be entered (other logic is removed for brevity).
$("input").keydown(function (event) {
var key = event.keyCode;
if ((key < 48 || key > 57) && (key < 96 || key > 105) || event.shiftKey) {
event.preventDefault();
}
});
This code works fine in English keyboards but on French keyboards the shift key is used so the logic fails there. If i remove the shift the logic fails in english keyboards.
Is there a way to detect a number is being pressed in the keydown event that will work on any type of keyboard?
Thanks
Use a custom function to check if the value of the keydown is numeric. From this previous answer (Validate decimal numbers in JavaScript - IsNumeric()):
function isNumber(n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
And your handler UPDATED:
$("input").keydown(function (event) {
var code = event.keyCode;
//Allows left and right arrows, backspace, and delete
if(code == 37 || code == 39 || code == 8 || code == 46)
return;
var character = String.fromCharCode(code);
if(event.shiftKey || !isNumber(character)){
event.preventDefault();
}
});
I have found that event.key works better than event.keyCode. The event handler needs to be onkeydown for it to work properly. The check for whether it's a number needs to come first. Here's my code. Tested to work on IE11, Edge, Chrome, and Firefox.
$("input").keydown(function (event) {
var code = event.keyCode;
var key = event.key;
if (!isNaN(Number(key)))
return;
// allow backspace, delete, left & right arrows, home, end keys
if (code == 8 || code == 46 || code == 37 || code == 39 || code == 36 || code == 35) {
return;
} else {
evt.preventDefault();
}
});
#HostListener('keydown', ['$event']) onKeyDown(event) {
if ((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
} else if (!this.isNumber(e.key)) {//For french keyboard
e.preventDefault();
}
}
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
I had a similar problem because of 2 different keyboards. And I solve that by checking if is not a number in the key value instead of the keyCode value.
Would this work?
$("input").bind("propertychange input textInput", function() {
this.value = this.value.replace(/[^\d.]/g, "");
});
Of course, this trims the value after the input event, so I'm not sure if that's what you want

how to disable the function of ESC key in JavaScript?

In my chat application there are some text fields which gets the user login details.
when filling the user details,If user suddenly pressed the ESC key,the data will be lost.
I need to disable the function of ESC key ? which event I need to use ? how can I do that.
my Java Script code is ,
function esc(e){
e = e || window.event || {};
var charCode = e.charCode || e.keyCode || e.which;
if(charCode == 27){
return false;
}
}
Searched a lot in Stack overflow and google.Nothing worked.Please any one help me to do that . Thanks..
You can bind an eventlistener to your input field to catch the Event when Esc is pressed and supress it.
document.querySelector("input").addEventListener("keydown",function(e){
var charCode = e.charCode || e.keyCode || e.which;
if (charCode == 27){
alert("Escape is not allowed!");
return false;
}
});
Example
I got the solution to control the " F5 , Esc , BackSpace(BS) " keys with the following code.
My Java Script code will be ,
document.attachEvent("onkeydown", win_onkeydown_handler);
function win_onkeydown_handler() {
switch (event.keyCode) {
case 116 : // 'F5'
event.returnValue = false;
event.keyCode = 0;
break;
case 27: // 'Esc'
event.returnValue = false;
event.keyCode = 0;
break;
case 08: // 'BackSpace'
if (event.srcElement.tagName == "INPUT"
|| event.srcElement.tagName == "TEXTAREA") {
} else {
event.returnValue = false;
event.keyCode = 0;
}
break;
}
}
Thanks who are all supported me to do this and for your suggestions.
I have used this for a login popup code:
jQuery(document).keyup(function(e){
if(e.keyCode==27 && popupStatus==1){
// alert('not allowed !!!');
// or any other code
return false;
}
});
I have done something similar using jquery to limit entry to numbers
$(inputBox).keydown(function(event) {
// Allow only backspace and delete
var allowed_keys = [
46, // delete
8, // backspace
];
if ($.inArray(event.keyCode, allowed_keys) != -1) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});

How to catch event.keyCode and change it to another keyCode?

I have checked other questions here at SO, however they do not answer my question. I want to simply catch certain keyCode and replace it with another. I am working with characters, not white spaces, and I do not need to loose focus or the like.
Below is my code. But you can replace those keyCodes with your (eg. when capital "A" is pressed, it should replace with zero 0, etc.). The idea is to replace the keyCode.
phrase.keypress(function(event)
{
if (event.shiftKey)
{
switch (event.keyCode)
{
// Cyrillic capitalized "Н" was pressed
case 1053: event.keyCode = 1187; event.charCode = 1187; event.which = 1187; break;
// Cyrillic capitalized "О" was pressed
case 1054: event.keyCode = 1257; event.charCode = 1257; event.which = 1257; break;
// Cyrillic capitalized "У" was pressed
case 1059: event.keyCode = 1199; event.charCode = 1199; event.which = 1199; break;
}
}
});
I tried with keydown and keyup as well. They do not alter the keyCode. How can I do that?
P.S. If possible, I am looking for a solution which does not "event.preventDefault() and manually insert desired key to input field, then move cursor to the end". I want cleaner and "right" solution. Thank you.
Keyboard event properties are all READ-only. You cannot capture one keyCode and change it to another.
See reference from MDN - Keyboard Events - All are read only can't be set.
As you mentioned in your post. -- If you wan't to handle, then you have to stop browser default key press and set the desired value to the element yourself.
While the properties on the KeyboardEvent instance is READ ONLY, you can override KeyboardEvent's prototype and create a getter for whatever you want to change. Here is an example which changes the keycodes of hjkl to act like arrow keys.
Object.defineProperty(KeyboardEvent.prototype, 'keyCode', {
get: function() {
switch (this.key) {
case 'h': return 37; // left
case 'j': return 40; // down
case 'k': return 38; // up
case 'l': return 39; // right
default: return this.which
}
}
})
I am using the following code to achieve the same result as if I had changed the keyCode, without actually being able to change it.
function inputValidation() {
var srcField = event.srcElement;
var sKey = event.keyCode;
var inputLetter = String.fromCharCode(sKey);
if (typeof(srcField) !== "undefined" && srcField !== null) {
inputLetter = transformInput(inputLetter);
var caretPos = srcField.selectionStart;
var startString = srcField.value.slice(0, srcField.selectionStart);
var endString = srcField.value.slice(srcField.selectionEnd, srcField.value.length);
srcField.value = startString + inputLetter + endString;
setCaretPosition(srcField, caretPos+1); // '+1' puts the caret after the input
event.preventDefault ? event.preventDefault() : event.returnValue = false; //for IE8
}
}
srcField.selectionStart gives the starting position of the text you have selected and srcField.selectionEnd gives the end position of the selection, if you haven't selected any text srcField.selectionStart equals srcField.selectionEnd.
The function setCaretPosition came from this answer by kd7. I only changed it to make it receive the element instead of its Id
function setCaretPosition(elem, caretPos) {
if (elem != null) {
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else
elem.focus();
}
}
}
you can change value as manuel and handle keypress. if you want to check key declare a variable and check your keycode.
this.event.target.value = this.event.target.value + ".";
return false;
full code:
function isNumberKeyDec(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var apos = 0;
if (charCode == 44) {
apos = 1;
charCode = 46;
}
if (this.event.target.value.length == 0 && charCode == 46) {
return false;
}
if (this.event.target.value.length == 1 && this.event.target.value == "0" && charCode == 48) {
return false;
}
if (this.event.target.value.length == 1 && this.event.target.value == "0" && charCode != 46) {
this.event.target.value = "";
}
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) {
return false;
}
if (charCode == 46 && this.event.target.value.indexOf(".") != -1) {
return false;
}
if (this.event.target.value.indexOf(".") != -1) {
if (this.event.target.value.substring(this.event.target.value.toString().indexOf(".")).length >= 2) {
return false;
}
}
if (this.event.target.value.indexOf(".") == -1 && charCode != 46) {
if (this.event.target.value.length >= 3 && charCode != 46) {
return false;
}
}
if (apos == 1) {
this.event.target.value = this.event.target.value + ".";
return false;
}
return true;
}

Disable backspace and delete key with javascript in IE

Anyone know how can I disable backspace and delete key with Javascript in IE? This is my code below, but seems it's not work for IE but fine for Mozilla.
onkeydown="return isNumberKey(event,this)"
function isNumberKey(evt, obj)
{
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode == 8 || charCode == 46) return false;
return true;
}
This event handler works in all the major browsers.
function onkeyup(e) {
var code;
if (!e) var e = window.event; // some browsers don't pass e, so get it from the window
if (e.keyCode) code = e.keyCode; // some browsers use e.keyCode
else if (e.which) code = e.which; // others use e.which
if (code == 8 || code == 46)
return false;
}
You can attach the event to this function like:
<input onkeyup="return onkeyup()" />
update based on #JoeCoders comment and the 'outdatedness' of my answer, I revised it.
document.querySelector([text input element]).onkeydown = checkKey;
function checkKey(e) {
e = e || event;
return !([8, 46].indexOf(e.which || e.keyCode || e.charCode) > -1);
}
See also this jsFiddle
This code cancels backspace action.
window.onkeydown = function (event) {
if (event.which == 8) {
event.preventDefault(); // turn off browser transition to the previous page
// put here code you need
};
};
$(document).keydown(function(e) {
if (e.keyCode === 8) {
var element = e.target.nodeName.toLowerCase();
if ((element != 'input' && element != 'textarea') || $(e.target).attr("readonly")) {
return false;
}
}
});

Categories