Firefox keydown backspace issue - javascript

I'm building a terminal emulation and running into an issue with capturing backspace in Firefox. I'm able to nab the first backspace and remove the last character on the input at the prompt, but it won't persist and remove more than one character.
Actual website: http://term.qt.io/
Replication here: http://jsfiddle.net/BgtsE/1/
JavaScript code
function handleKeys(e){
var evt = e || window.event;
var key = evt.charCode || evt.keyCode;
if(evt.type == "keydown")
{
curr_key = key;
if(key == 8)
{
evt.preventDefault();
if(0 < $('body').text().length)
$('body').text($('body').text().slice(0,-1));
}
}
else if(evt.type == "keypress")
{
if(97 <= key && key <= 122)
{
if(curr_key != key)
$('body').append(String.fromCharCode(key));
}
else
$('body').append(String.fromCharCode(key));
}
}
$(function(){
$('html').live({
keydown:function(e){
handleKeys(e);
},
keypress:function(e){
handleKeys(e);
}
})
})​

Try this: http://jsfiddle.net/NBZG8/1/
You'll need to handle backspace in both keydown and keypress to support Chrome and Firefox
function handleKeys(e){
var evt = e || window.event;
var key = evt.charCode || evt.keyCode;
if (evt.type == "keydown") {
curr_key = key;
if(key == 8 && !$.browser.mozilla) {
backspaceHandler(evt);
}
} else if (evt.type == "keypress") {
if (key == 8) {
backspaceHandler(evt);
} else if (97 <= key && key <= 122) {
if(curr_key != key) {
$('body').append(String.fromCharCode(key));
}
} else {
$('body').append(String.fromCharCode(key));
}
}
}
function backspaceHandler(evt) {
evt.preventDefault();
if(0 < $('body').text().length) {
$('body').text($('body').text().slice(0,-1));
}
};
$(function(){
$('html').live({
keydown : handleKeys,
keypress : handleKeys
})
})​

In firefox Windows 17.0.1 any value returned by $("selector").text() has an added new line character appended to the end. So the substring didn't work for me:
<html>
<head>
<title>test</title>
<script src="jquery.js"></script>
<script>
$("document").ready(function(){
console.log("body text seems to have a new line character");
console.log(($('body').text()[5]=="\n"));
});
function handleKeys(e){
var evt = e || window.event;
var key = evt.charCode || evt.keyCode;
if(evt.type == "keydown")
{
curr_key = key;
if(key == 8)
{
evt.preventDefault();
if(0 < $('body').text().length)
// next line works, you might trim the \n if it's there at the end
//$('body').text($('body').text().slice(0,-2));
// this one didn't work for me
$('body').text($('body').text().substring(0,$('body').text().length-1));
}
}
else if(evt.type == "keypress")
{
if(97 <= key && key <= 122)
{
if(curr_key != key)
$('body').append(String.fromCharCode(key));
}
else
$('body').append(String.fromCharCode(key));
}
}
$(function(){
$('html').live({
keydown:function(e){
handleKeys(e);
},
keypress:function(e){
handleKeys(e);
}
})
})
</script>
</head>
<body>12345</body>
</html>

I had the same issue with keypress on mozilla.
Thanks to this subject it solves my problem so I'll post my code if anyone try to do the same thing as me.
In my exemple I try to auto space when the user type two numbers, and it didn't work in Firefox so that's my code :
$(function() {
$('#field1, #field2').on('keypress',function(event) {
event = event || window.event;
var charCode = event.keyCode || event.which,
lgstring = $(this).val().length,
trimstring;
if(charCode === 8) {
event.returnValue = false;
if(event.preventDefault)
event.preventDefault();
if(0 < $(this).val().length) {
$(this).val($(this).val().slice(0,-1));
}
}
else if(((charCode > 31) && (charCode < 48 || charCode > 57)) || lgstring >= 14) {
event.returnValue = false;
if(event.preventDefault)
event.preventDefault();
}
else {
trimstring = $(this).val().replace(/ /g,"");
if((lgstring !== 0) && (trimstring.length % 2) === 0 ) {
$(this).val($(this).val() + ' ');
}
}
});
});
I noticed that Mozilla handle the backspace as a keypress where Chrome don't.
Sorry for my English I'm French

$('#id').keypress(function(e) {
if(e.charCode > 0 || e.keyCode === 8){
if(e.keyCode === 8){
return true;
}else if((e.charCode !== 0) && ((e.charCode > 57 && e.charCode < 65)){
return false;
}
}else if((e.keyCode !== 0) && ((e.keyCode > 57 && e.keyCode < 65)){
return false;
}
});

Related

Disable Ctrl key in IE 8

I want to disable the ctrl key in the IE browser.I had tried some solution using javascript but nothing is working can someone please help me to find out the solution
document.onkeydown = function () {
if (event.keyCode == 17) alert('Ctrl Key is disabled');
};
document.onkeydown = function(e) {
if (e.altKey && (e.keyCode === 36)) {//Alt+home blocked.
return false;
}
if (e.altKey && (e.keyCode === 70)) {//Alt+f blocked.
return false;
}
};
function hookKeyboardEvents(e) {
// get key code
var key_code = (window.event) ? event.keyCode : e.which;
// case :if it is IE event
if (window.event)
{
if (!event.shiftKey && !event.ctrlKey) {
window.event.returnValue = null;
event.keyCode = 0;
}
}
// case: if it is firefox event
else
e.preventDefault();
}
window.document.onkeydown = hookKeyboardEvents;
function Disable_Control_C() {
var keystroke = String.fromCharCode(event.keyCode).toLowerCase();
if (event.ctrlKey && (keystroke == 'c' || keystroke == 'v' || keystroke == 'p' || keystroke == 's' || keystroke == 'u')) {
alert("this function is disabled");
event.returnValue = false; // disable Ctrl+C
}
}
<body onkeydown="javascript:Disable_Control_C()">
this is what i do it to run in the IE...

Number in textfield should be autoformatted only after user clicks outside the textbox?

I have a problem. Basically, what happens in my case is that the numbers in my textbox are autoformatted as I type. I don't want this to happen. What I want is that the numbers should be autoformatted only when the user clicks outside the textbox.
In my input tag I have :
onkeyup="format(event, this);"
My javascript function is :
function format(e, obj) {
if (e.keyCode == 36) {
press1(obj);
}
if (e.keyCode == 13) {
return false;
}
if ((e.keyCode <= 34) || (e.keyCode >= 46 && e.keyCode < 58) || (e.keyCode >= 96 && e.keyCode <= 105)) { // //alert(e.keyCode);
obj.value = CommaFormatted(obj.value);
} else {
if (e && e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
return false;
}
}
where the press1 function is:
function press1(textControlID) {
var text = textControlID;
if (text.getAttribute("maxlength") == text.value.length) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
return true;
}
if (text != null && text.value.length > 0) {
if (text.createTextRange) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
} else if (text.setSelectionRange) {
var textLength = text.value.length;
text.setSelectionRange(textLength, textLength);
}
}
}
I really hope this could be solved. Please!
You could change onkeyup to onblur, which is the event that gets fired when the control loses focus - clicking out of it.
The onkeyup event fires with every keypress.

How to avoid entering special characters in JavaScript

On html I have one input box in which I just want to enter numeric values. I used following function:
function allowNumbersOnly(event,locale) {
if(locale=='en' && (event.keyCode==190 || event.keyCode==110)){
return true;
}
else if(locale=='nl' && (event.keyCode==188 || event.keyCode==190 || event.keyCode==110)){
return true;
}
if(event.keyCode==189 || (event.keyCode==109) ){
return true;
}
var key = event.charCode || event.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
if (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)){
}else{
event.preventDefault();
}
}
This code works fine. But when I am pressing shift key+ any number from keyboard then special character gets entered. Can anyone tell me how to solve this issue?
Try the following function
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
If you are using HTML5 just try
<input type="number">
Try like this:
function blockspecialcharacter(e) {
var key= document.all ? key= e.keyCode : key= e.which;
return ((key > 64 && key < 91) || (key> 96 && key< 123) || key== 8 || key== 32 || (key>= 48 && key<= 57));
}
Check demo here
shiftKey event attribute returns a Boolean value that indicates whether or not the "SHIFT" key was pressed
if (event.shiftKey==1)
{
alert("The shift key was pressed!")
}
else
{
alert("The shift key was NOT pressed!")
}
so you can exit from your function if shift is pressed using value of event.shiftKey
// in your code
function allowNumbersOnly(event,locale) {
if (event.shiftKey==1) {
return false;
} // RETURN if shift key got clicked.
if (locale=='en' && (event.keyCode==190 || event.keyCode==110)) {
return true;
}
else if (locale=='nl' && (event.keyCode == 188 ||
event.keyCode == 190 ||
event.keyCode == 110)) {
return true;
}
if (event.keyCode==189 || (event.keyCode==109)) {
return true;
}
var key = event.charCode || event.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
if (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)) {
}
else {
event.preventDefault();
}
}
Try this:
function blockSpecialChars(e){
var e = e || window.event;
var k = e.which || e.keyCode;
var s = String.fromCharCode(k);
return !/^[\\\"\'\;\:\>\|~`!##\$%^&*\(\)]$/i.test(s);
}
Add or remove the special characters from the above code to make it as you need.

Working with multiple key press events (windows key)

While working with the multiple keypress events i found this code which worke fine
$(document).bind('keypress', function(event) {
if( event.which === 65 && event.shiftKey ) {
alert('you pressed SHIFT+A');
}
});
But to make it to work wth combinig with windows key... like
event.which === 65 && event.windowsKey
it failed...
Is there any option to make it work with windows key?
if it is a mac machine there is no key as windows..so what could be the alternate option for windows key in mac
Use keyup event.
On a Mac left Command is which = 91, right Command is which = 93. I can't tell what are those on Windows, but you can test it yourself. As #ian commented they should be 91 and 92 respectively.
To test
$(document).on('keyup', function(e) {
var modKey = "";
if (e.shiftKey) modKey += "shiftKey,";
if (e.ctrlKey) modKey += "ctrlKey,";
if (e.altKey) modKey += "altKey,";
if (e.metaKey) modKey += "metaKey,";
console.log ("which: " + e.which + " modkey: " + modKey );
});
UPDATE: Try use keydown event and event.metaKey
$(document).on('keydown', function(e) {
if(e.which === 65 && event.metaKey ) {
console.log ("You pressed Windows + A");
}
});
Remember the key you pressed before. Like if you press shift. get a boolean or something to shiftPressed = true on a onKeyRelease make it false again. That way you can check if shiftPressed == true && aPressed == true before doing something
I made something a while ago for a little WASD game. Perhaps it makes more sense if you see the code:
var up = false;
var down = false;
var left = false;
var right = false;
function keyUp(e) {
keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode == 37 || keyCode == 65) {
left = false;
}
if (keyCode == 38 || keyCode == 87) {
up = false;
}
if (keyCode == 39 || keyCode == 68) {
right = false;
}
if (keyCode == 40 || keyCode == 83) {
down = false;
}
}
function forceStopMoving() {
left = false;
up = false;
right = false;
down = false;
}
function keyDown(e) {
keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode == 37 || keyCode == 65) {
left = true;
}
if (keyCode == 38 || keyCode == 87) {
up = true;
}
if (keyCode == 39 || keyCode == 68) {
right = true;
}
if (keyCode == 40 || keyCode == 83) {
down = true;
}
}

jquery only allow input float number

i'm making some input mask that allows only float number. But current problem is I can't check if multiple dots entered. Can you check those dots and prevent it for me?
Live Code: http://jsfiddle.net/thisizmonster/VRa6n/
$('.number').keypress(function(event) {
if (event.which != 46 && (event.which < 47 || event.which > 59))
{
event.preventDefault();
if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
event.preventDefault();
}
}
});
You can check for the period in the same statement.
Also, you need to use the val method to get the value of the element.
Also, you want to check for the interval 48 to 57, not 47 to 59, otherwise you will also allow /, : and ;.
jQuery(document).ready(function() {
$('.float-number').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Enter Number:
<input type="text" name="number" value="" class="float-number">
</body>
</html>
I think you guys have missed the left right arrows, delete and backspace keys.
$('.number').keypress(function(event) {
if(event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46)
return true;
else if((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
event.preventDefault();
});
I think everybody forgot the case of pasting text with the mouse, in which you can't detect the keystrokes, because there's none. Here's another approach I have been working on.
// only integer or float numbers (with precision limit)
// example element: <input type="text" value="" class="number" name="number" id="number" placeholder="enter number" />
$('.number').on('keydown keypress keyup paste input', function () {
// allows 123. or .123 which are fine for entering on a MySQL decimal() or float() field
// if more than one dot is detected then erase (or slice) the string till we detect just one dot
// this is likely the case of a paste with the right click mouse button and then a paste (probably others too), the other situations are handled with keydown, keypress, keyup, etc
while ( ($(this).val().split(".").length - 1) > 1 ) {
$(this).val($(this).val().slice(0, -1));
if ( ($(this).val().split(".").length - 1) > 1 ) {
continue;
} else {
return false;
}
}
// replace any character that's not a digit or a dot
$(this).val($(this).val().replace(/[^0-9.]/g, ''));
// now cut the string with the allowed number for the integer and float parts
// integer part controlled with the int_num_allow variable
// float (or decimal) part controlled with the float_num_allow variable
var int_num_allow = 3;
var float_num_allow = 1;
var iof = $(this).val().indexOf(".");
if ( iof != -1 ) {
// this case is a mouse paste (probably also other events) with more numbers before the dot than is allowed
// the number can't be "sanitized" because we can't "cut" the integer part, so we just empty the element and optionally change the placeholder attribute to something meaningful
if ( $(this).val().substring(0, iof).length > int_num_allow ) {
$(this).val('');
// you can remove the placeholder modification if you like
$(this).attr('placeholder', 'invalid number');
}
// cut the decimal part
$(this).val($(this).val().substring(0, iof + float_num_allow + 1));
} else {
$(this).val($(this).val().substring(0, int_num_allow));
}
return true;
});
Good for integer and float values. Plus, copy/paste clipboard event.
var el = $('input[name="numeric"]');
el.prop("autocomplete",false); // remove autocomplete (optional)
el.on('keydown',function(e){
var allowedKeyCodesArr = [9,96,97,98,99,100,101,102,103,104,105,48,49,50,51,52,53,54,55,56,57,8,37,39,109,189,46,110,190]; // allowed keys
if($.inArray(e.keyCode,allowedKeyCodesArr) === -1 && (e.keyCode != 17 && e.keyCode != 86)){ // if event key is not in array and its not Ctrl+V (paste) return false;
e.preventDefault();
} else if($.trim($(this).val()).indexOf('.') > -1 && $.inArray(e.keyCode,[110,190]) != -1){ // if float decimal exists and key is not backspace return fasle;
e.preventDefault();
} else {
return true;
};
}).on('paste',function(e){ // on paste
var pastedTxt = e.originalEvent.clipboardData.getData('Text').replace(/[^0-9.]/g, ''); // get event text and filter out letter characters
if($.isNumeric(pastedTxt)){ // if filtered value is numeric
e.originalEvent.target.value = pastedTxt;
e.preventDefault();
} else { // else
e.originalEvent.target.value = ""; // replace input with blank (optional)
e.preventDefault(); // retur false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="numeric" value="" placeholder="insert value">
[2017-10-31] Vanilla.js
let el = document.querySelector('input[name="numeric"]');
el.addEventListener('keypress',(event) => {
let k = event.key,
t = isNaN(k),
sc = ['Backspace'].indexOf(k) === -1,
d = k === '.',dV = el.value.indexOf('.') > -1,
m = k === '-',mV = el.value.length > 0;
if((t && sc) && ((d && dV) || (m && dV) || (m && mV) || ((t && !d) && (t && !m)))){event.preventDefault();}
},false);
el.addEventListener('paste',(event) => {
if(event.clipboardData.types.indexOf('text/html') > -1){
if(isNaN(event.clipboardData.getData('text'))){event.preventDefault();}
}
},false);
<input type="text" name="numeric">
Your code seems quite fine but overcomplicated.
First, it is $(this).val().indexOf, because you want to do something with the value.
Second, the event.which == 46 check is inside an if clause that's only passed when event.which != 46, which can never be true.
I ended up with this which works: http://jsfiddle.net/VRa6n/3/.
$('.number').keypress(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46
&& $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
});
I found this way to do this,
$.validator.addMethod("currency", function (value, element) {
return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value);
}, "Please specify a valid amount");
https://gist.github.com/jonkemp/9094324
HTML
<input type="text" onkeypress="return isFloatNumber(this,event)" />
Javascript
function isFloatNumber(item,evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode==46)
{
var regex = new RegExp(/\./g)
var count = $(item).val().match(regex).length;
if (count > 1)
{
return false;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
jsfiddle.net
Using JQuery.
$(document).ready(function()
{
//Only number and one dot
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
onlyDecimal("#TextBox1", 3) ;
});
One-more plugin, based on Carlos Castillo answer
https://github.com/nikita-vanyasin/jquery.numberfield.js
Adds method to jQuery object:
$('input.my_number_field').numberField(options);
where options is (you can pass any or no options):
{
ints: 2, // digits count to the left from separator
floats: 6, // digits count to the right from separator
separator: "."
}
Using jQuery and allowing negative floats :
// Force floats in '.js_floats_only' inputs
$(document).ready(function() {
$('.js_floats_only').each(function() {
// Store starting value in data-value attribute.
$(this).data('value', this.value);
});
});
$(document).on('keyup', '.js_floats_only', function() {
var val = this.value;
if ( val == '-' ) {
// Allow starting with '-' symbol.
return;
} else {
if ( isNaN(val) ) {
// If value is not a number put back previous valid value.
this.value = $(this).data('value');
} else {
// Value is valid, store it inside data-value attribute.
$(this).data('value', val);
}
}
});
For simple cases and without hardcoding some html instructions would fit that pretty enough
<input type="number" step="0.01"/>
$('.number').keypress(function(event){
if($.browser.mozilla == true){
if (event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9 || event.keyCode == 16 || event.keyCode == 46){
return true;
}
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
This works in all browsers.
<input type="text" data-textboxtype="numeric" />
<script>
$(document).on('keydown', '[data-textboxtype="numeric"]', function (e) {
// Allow: backspace, delete, tab, escape, enter and . and -
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 109, 189]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return true;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
return false;
}
return true;
});
</script>
Below Code I am allowing only Digits and Dot symbol.
ASCII characters number starts in 47 and ends with 58 and dot value is 190.
$("#Experince").keyup(function (event) {
debugger
if ((event.which > 47
&& event.which < 58) ||event.which== 190) {
if ($("#Experince").val().length > 3) {
}
} // prevent if not number/dot
else {
$("#Experince").val($("#Experince").val().slice(0, -1))
}
});

Categories