Why on this page:
https://jsfiddle.net/eddnhc5f/
When I press the key c on Firefox and Microsoft edge, the background is changed before the alert, but in Opera and Chrome, after I press confirm alert.
function getKeyup(key) {
if (key == null) {
keycode = event.keyCode;
// To Mozilla
} else {
keycode = key.keyCode;
}
}
function TEST() {
document.body.style.backgroundColor = "BLACK";
alert('Hello');
return false;
}
function getKey(key) {
if (key == null) {
keycode = event.keyCode;
// To Mozilla
} else {
keycode = key.keyCode;
}
if (keycode == 67) {
//alert(condcheck);
TEST();
return false;
}
}
$(document).ready(function() {
$(document).keydown(function(eventObj) {
getKey(eventObj);
});
$(document).keyup(function(eventObj) {
getKeyup(eventObj);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
TEST
check out this demo
I did change in TEST() function.
function getKeyup(key){
if ( key == null ) {
keycode = event.keyCode;
// To Mozilla
} else {
keycode = key.keyCode;
}
}
function TEST()
{
//document.body.style.backgroundColor = "BLACK";
alert('Hello');
document.body.style.backgroundColor = "BLACK";
return false;
}
function getKey(key){
if ( key == null ) {
keycode = event.keyCode;
// To Mozilla
} else {
keycode = key.keyCode;
}
if (keycode == 67){
//alert(condcheck);
TEST();
return false;
}
}
$(document).ready( function (){
$(document).keydown(function (eventObj){
getKey(eventObj);
});
$(document).keyup(function (eventObj){
getKeyup(eventObj);
});
});
I have some issues: I have this : (in a function..)
var space = 0;
setInterval(space, 20);
var keys = {}
$(document).keydown(function(e) {
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
delete keys[e.keyCode];
});
function space() {
for (var direction in keys) {
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
space++;
console.log(space);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
32 == Space key, but I saw in the console that space is pressed 3 times (space == 3), keyup keypress and keydown (I think), how can I have just "space = 1" when space is pressed ?
What seems to be happening is that since it's running every 20 ms, as you hold down the space bar the space function is continuously incrementing the count. I added a flag to prevent another execution until the key is released and it works fine. Really you should just use the keypress event and check there if the keyCode === 32 to track your count. Fewer events will be fired. If you want to see what was happening you can comment out the flag and check the console.
var spaceCount = 0;
var running = false;
var keys = {}
$(document).keydown(function(e) {
console.log("keycode", e.keyCode);
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
console.log("keyup")
delete keys[e.keyCode];
running = false;
});
function space() {
if(running) return;
for (var direction in keys) {
running = true;
console.log(direction);
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
spaceCount++;
console.log("count: " + spaceCount);
console.log(keys);
}
}
}
setInterval(space, 20);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I hope that will be helpful:
var space = 0;
var keys = {};
var keys2 = {};
$(document).keydown(function(e) {
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
keys[e.keyCode] = false;
});
setInterval(function(){spacing()}, 20);
function spacing() {
if (keys[32] && !keys2[32])
{
space++;
keys2[32] = true;
}
else if(!keys[32])
{
keys2[32] = false;
}
console.log(space);
}
I'd like to have the phone number field on this website only accept numbers or digits. I do not have access to edit the HTML code, so can this be done with jQuery by targeting the field's ID? If so, how can it be done?
I've already tried a few suggestions on this site and none have worked so far.
Thanks in advance for any assistance!
Similar to Jeroen's solution, here's one that is a little cleaner because rather than replacing the invalid input, it completely prevents it.
$('#nbr').on('keypress', function(ev) {
var keyCode = window.event ? ev.keyCode : ev.which;
//codes for 0-9
if (keyCode < 48 || keyCode > 57) {
//codes for backspace, delete, enter
if (keyCode != 0 && keyCode != 8 && keyCode != 13 && !ev.ctrlKey) {
ev.preventDefault();
}
}
});
http://jsfiddle.net/PUQGQ/
Use jQuery to hook into the textfield's keypress event. In the handler, read the textfield's value and filter out everything that you don't want using a regex replace.
Update: untested example to illustrate:
jQuery("#myPhonefield").keypress(function(){
var value = jQuery(this).val();
value = value.replace(/[^0-9]+/g, '');
jQuery(this).val(value);
});
You can use jquery's keypress as recommended by Jeroen; however, I would recommend doing it without using a regex. Something along these lines should work for you:
$('#test').on('keypress', function(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});
Live DEMO
To handle pasting, you can perform a regular expression check on blur or focusout:
$('#test').on('focusout', function() {
var value = $(this).val();
$(this).val(value.replace(/[^0-9]/g, ''));
});
Live Demo
http://jsfiddle.net/charlescarver/hTMdF/
$("input[type=submit]").click(function() {
var regex = /\d/g;
var text = $("input[type=text]").val();
if (regex(text)) {
alert("yes");
}
});
This will alert you if a number is found.
Here is my solution (It also validates data/values copy&pasted):
function InputValidator(input, validationType, validChars) {
if (input === null || input.nodeType !== 1 || input.type !== 'text' && input.type !== 'number')
throw ('Please specify a valid input');
if (!(InputValidator.ValidationType.hasOwnProperty(validationType) || validationType))
throw 'Please specify a valid Validation type';
input.InputValidator = this;
input.InputValidator.ValidCodes = [];
input.InputValidator.ValidCodes.Add = function (item) {
this[this.length] = item;
};
input.InputValidator.ValidCodes.hasValue = function (value, target) {
var i;
for (i = 0; i < this.length; i++) {
if (typeof (target) === 'undefined') {
if (this[i] === value)
return true;
}
else {
if (this[i][target] === value)
return true;
}
}
return false;
};
var commandKeys = {
'backspace': 8,
'tab': 9,
'enter': 13,
'shift': 16,
'ctrl': 17,
'alt': 18,
'pause/break': 19,
'caps lock': 20,
'escape': 27,
'page up': 33,
'page down': 34,
'end': 35,
'home': 36,
'left arrow': 37,
'up arrow': 38,
'right arrow': 39,
'down arrow': 40,
'insert': 45,
'delete': 46,
'left window key': 91,
'right window key': 92,
'select key': 93,
/*creates Confusion in IE */
//'f1': 112,
//'f2': 113,
//'f3': 114,
//'f4': 115,
//'f5': 116,
//'f6': 117,
//'f7': 118,
//'f8': 119,
//'f9': 120,
//'f10': 121,
//'f11': 122,
//'f12': 123,
'num lock': 144,
'scroll lock': 145,
};
commandKeys.hasValue = function (value) {
for (var a in this) {
if (this[a] === value)
return true;
}
return false;
};
function getCharCodes(arrTarget, chars) {
for (var i = 0; i < chars.length; i++) {
arrTarget.Add(chars[i].charCodeAt(0));
}
}
function triggerEvent(name, element) {
if (document.createEventObject) {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on' + name, evt)
}
else {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(name, true, true); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
if (validationType == InputValidator.ValidationType.Custom) {
if (typeof (validChars) === 'undefined')
throw 'Please add valid characters';
getCharCodes(input.InputValidator.ValidCodes, validChars);
}
else if (validationType == InputValidator.ValidationType.Decimal) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789.');
}
else if (validationType == InputValidator.ValidationType.Numeric) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789');
}
input.InputValidator.ValidateChar = function (c) {
return this.ValidCodes.hasValue(c.charCodeAt(0));
}
input.InputValidator.ValidateString = function (s) {
var arr = s.split('');
for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';
}
}
return arr.join('');
}
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}
function getCaretPosition(i) {
if (!i) return;
if ('selectionStart' in i) {
return i.selectionStart;
}
else {
if (document.selection) {
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -i.value.length);
return sel.text.length - selLen;
}
}
}
function setCursor(node, pos) {
var node = (typeof (node) === "string" || node instanceof String) ? document.getElementById(node) : node;
if (!node) {
return false;
}
else if (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
} else if (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
return true;
}
return false;
}
function validateActive() {
if (input.isActive) {
var pos = getCaretPosition(input);
var arr = input.value.split('');
for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';
if (pos > i)
pos--;
}
}
console.log('before : ' + input.value);
input.value = arr.join('');
console.log('after : ' + input.value, input);
setCursor(input, pos);
setTimeout(validateActive, 10);
}
}
bindEvent(input, 'keypress', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;
if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
});
bindEvent(input, 'keyup', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;
if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
});
bindEvent(input, 'change', function (e) {
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
if (input.value !== dt)
triggerEvent('change', input);
});
bindEvent(input, 'blur', function (e) {
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
input.isActive = false;
if (input.value !== dt)
triggerEvent('blur', input);
});
bindEvent(input, 'paste', function (e) {
var evt = e || window.event;
var svt = input.value;
if (evt && evt.clipboardData && evt.clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
if (/text\/html/.test(evt.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/html');
input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else if (/text\/plain/.test(e.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/plain');
input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else {
input.value = '';
}
waitforpastedata(input, svt);
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
input.value = '';
waitforpastedata(input, svt);
return true;
}
});
bindEvent(input, 'select', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});
bindEvent(input, 'selectstart', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});
/* no need to validate wile active,
removing F keys fixed IE compatability*/
//bindEvent(input, 'fucus', function (e) {
// input.isActive = true;
// validateActive();
//});
//validate current value of the textbox
{
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
//trigger event to indicate value has changed
if (input.value !== dt)
triggerEvent('change', input);
}
function waitforpastedata(elem, savedcontent) {
if (elem.value !== '') {
var dt = input.value;
elem.value = elem.InputValidator.ValidateString(elem.value);
if (input.value !== dt)
triggerEvent('change', input);
}
else {
var that = {
e: elem,
s: savedcontent
}
that.callself = function () {
waitforpastedata(that.e, that.s)
}
setTimeout(that.callself, 10);
}
}
}
InputValidator.ValidationType = new (function (types) {
for (var i = 0; i < types.length; i++) {
this[types[i]] = types[i];
}
})(['Numeric', 'Custom', 'Decimal']);
To apply it to an input, do the following :
new InputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Decimal);/* Numeric or Custom */
If you specify Custom as the validation type you have to specify the valid characters.
eg :
new InputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Custom,'1234abc');
I'm new to Javascript and I'm trying to make the following code scan to see if a textbox with an id="lessonNum" is active, if it is not i would like to send a .click to a submit button with an id="A" when I press 'a' on the keyboard. Right now when I select the textbox I get an alert, but when I don't have it selected it doesn't pick up my keydown. Please Help!
function GetActive () {
if (document.activeElement.id == 'lessonNum') {
alert('lessonNum is active');
var b1=new Boolean(1);
} else {
var b1=new Boolean(0);
}
}
document.addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
var keyCode = e.keyCode;
if(keyCode==65) {
if(b1==0) {
alert('a has been pressed');
document.getElementById('A').click();
}
}
}
In your code:
> function GetActive () {
> if (document.activeElement.id == 'lessonNum') {
> alert('lessonNum is active');
> var b1 = new Boolean(1);
the above line creates a local variable called b1 and assigns a new boolean object. I think you just want a primitive, so:
var b1 = true;
or the whole if..else statement can be replaced with:
var b1 = document.activeElement.id == 'lessonNum';
if (b1) alert('lessonNum is active');
Note that getActive is never called so b1 is never set anyway.
In keyDownTextField you have:
> if(b1==0) {
> alert('a has been pressed');
however b is local to GetActive so a reference error will be thrown. The simple solution is to make b global, a little more work but better though to hold it in a closure.
e.g.
(function(global) {
var b1;
var getActive = function () {
b1 = document.activeElement && document.activeElement.id == 'lessonNum';
if (b1) alert('lessonNum is active');
}
global.getActive = getActive;
var keyDownTextField = function (e) {
e = e || window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == 65) {
getActive(); // should it be called here?
if (b1) {
alert('a has been pressed');
document.getElementById('A').click();
}
}
}
global.keyDownTextField = keyDownTextField;
}(this));
window.onload = function() {
addEvent(document, 'keydown', keyDownTextField);
};
// Just a helper
function addEvent(el, evt, fn){
if (el.addEventListener) {
el.addEventListener(evt, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + evt, fn);
}
}
I got my keyboard working in a simple way:
rightPressed = false;
onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = true;
}
onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = false;
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
And it worked. Then i tried to put it all in a class:
function Tkeyboard(){
this.rightPressed = false;
this.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
}
this.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = false; }
}
$(document).keydown(this.onKeyDown);
$(document).keyup(this.onKeyUp);
}
In initialization I created an object:
keys = new Tkeyboard;
In main loop i put action:
if ( keys.rightPressed ) { rx+=1;}
And now it fails. The interesting part of the problem is that alert("boom!") is called, so variable should get modified too...
I would be grateful for any ideas.
The keydown/up callback loses its original scope when the it is actually run. You'll need to bind the callback to this. In the Prototype Framework, you would do this:
function Tkeyboard() {
this.rightPressed = false;
$(document).keydown(this.onKeyDown.bind(this));
$(document).keyup(this.onKeyUp.bind(this));
}
Tkeyboard.prototype.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
};
Tkeyboard.prototype.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = false; }
};
It should be similar in jQuery.
If you need an idea of how to build a full fledged keyboard class, check out the one I wrote.
In an event handler in jQuery (and in DOM events), this refers to the element the event is subscribed on (document in the sample). Use a closure if you want to refer to the original object.
function Tkeyboard(){
var self = this;
this.rightPressed = false;
this.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { self.rightPressed = true; alert("boom!"); }
}
this.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { self.rightPressed = false; }
}
$(document).keydown(this.onKeyDown);
$(document).keyup(this.onKeyUp);
}
this is set to the DOM element (in this case document) from which the event handler is called. In general, this is not bound to the object in javascript:
var a = {
f: function () {}
};
var b = { f: a.f};
var f = a.f;
a.f(); // this === a
b.f(); // this === b
f(); // this === window
One commonly used workaround is to bind this to a wrapper function:
function bind(func, that) {
return function() {
func.apply(that, arguments);
}
}
//...
$(document).keydown(bind(this.onKeyDown, this));
Or you could use closures:
function Tkeyboard() {
var that = this;
// use 'that' from here on
you can initiate new function it will work
function Tkeyboard() {
this.rightPressed = false;
this.onKeyDown = function (pressEvent) {
if (pressEvent.keyCode == 39) {
this.rightPressed = true;
console.log(this.rightPressed )
alert('boom')
}
}
this.onKeyUp = function (pressEvent) {
if (pressEvent.keyCode == 39) {
this.rightPressed = false;
console.log(this.rightPressed )
}
}
this.events = function(){
document.addEventListener('keydown', this.onKeyDown);
document.addEventListener('keyup', this.onKeyUp);
}
}
const keys = new Tkeyboard;
keys.events();