I want to write it in a better, optimized way. I thought maybe I should use jquery each function but not sure how to write it. Basically there are list of 7 buttons and both NUM keys and regular number keys are attached to related buttons.
the HTML is here http://jsfiddle.net/wAwed/1/
$(document).keydown(function (e) {
if ($(e.target).is('input') || $(".answerbtns").length != 0 ) { return }
/* keyboard 1 */
else if (e.keyCode == 97 || e.keyCode == 49 ) {
$("#.ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl00_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 2 */
if (e.keyCode == 98 || e.keyCode == 50 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl01_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 3 */
if (e.keyCode == 99 || e.keyCode == 51 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl02_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 4 */
if (e.keyCode == 100 || e.keyCode == 52 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl03_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 5 */
if (e.keyCode == 101 || e.keyCode == 53 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl04_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 6 */
if (e.keyCode == 102 || e.keyCode == 54 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl05_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 7 */
if (e.keyCode == 103 || e.keyCode == 55 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl06_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
});
sure, create a map of keycodes that link keycodes to the target element, then use a loop. Or use object key/value pairs. Here's a sample for two of them:
var keys = {
97: "#.ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl00_lbAnswers",
49: "#.ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl00_lbAnswers"
}
$(document).keydown(function (e) {
if ($(e.target).is('input') || $(".answerbtns").length != 0 ) { return }
/* keyboard 1 */
if (keys[e.keyCode]) {
$(keys[e.keyCode])[0].click();
e.stopPropagation();
return false;
}
});
And, if they all have the class "answerbtns", you can do this:
var numeric = [97,98,99,100,101,102,103];
var numpad = [49,50,51,52,53,54,55];
$(document).keydown(function (e) {
if ($(e.target).is('input') || $(".answerbtns").length == 0 ) { return }
/* keyboard 1 */
var index = $.inArray(e.which,numeric);
if ( index == -1 ) {
index = $.inArray(e.which,numpad);
}
if ( index != -1 ) {
$(".answerbtns")[index].click();
e.stopPropagation();
return false;
}
});
http://jsfiddle.net/wAwed/2/
This option reduces some code.
var custKeyCode = [97, 49, 98, 50];
if (e.keyCode == 97 || e.keyCode == 49 ) {
myid = "#.ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl00_lbAnswers";
}
if (e.keyCode == 98 || e.keyCode == 50 ) {
myid = "#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl01_lbAnswers";
}
......
......
for(var i=0; i<custKeyCode.length; i++){
if(custKeyCode[i] == e.keyCode){
$(myid)[0].click();
e.stopPropagation();
return false;
}
}
Related
i inserted inputs in a fieldset with max-length equals to 1 and i added to each of them a keyup and keydown event through eventListener. The problem appears when i type characters fast and the first character is duplicated.
`
document.addEventListener('DOMContentLoaded', () => { // everything is loaded
var after, before;
inputList = document.querySelectorAll('input[type=text][maxlength="1"]');
inputList.forEach(element => {
element.addEventListener('keydown', () => {
before = element.value;
});
element.addEventListener('keyup', (event) => {
after = element.value;
if(event.keyCode === 37) {
element.previousElementSibling.focus();
return;
}
if(event.keyCode === 39) {
element.nextElementSibling.focus();
return;
}
if(after.length == 1 && before.length == 0) {
try {
element.nextElementSibling.focus();
return;
} catch(TypeError) {
return;
}
}
if(event.keyCode === 8) {
element.previousElementSibling.focus();
return;
}
alert(event.keyCode);
if(before.length === 1 &&
((event.keyCode >= 65 && event.keyCode <= 90) || (event.keyCode >= 97 && event.keyCode <= 122) || (event.keyCode >= 48 && event.keyCode <= 57))
) {
element.nextElementSibling.value = String.fromCharCode(event.keyCode);
element.nextElementSibling.focus();
return;
}
});
})
});
How to check if iframe content is empty then then disable "enter key" and "space"
else if Enable.
DEMO HERE
var iframeContainerVal = $("#textEditor").contents().find("body").text();
var container = document.getElementById("textEditor").contentWindow;
function checkPress(){
alert('In Fn')
$(container).keypress(function(event){
if (event.keyCode == 10 || event.keyCode == 13 || event.keycode == 32 ) {
alert('aaa');
event.preventDefault();
}
});
}
if(iframeContainerVal == true) {
checkPress()
}
else {
alert('false')
}
Use return false;
function checkPress(){
alert('In Fn')
$(container).keypress(function(event){
if (event.keyCode == 10 || event.keyCode == 13 || event.keyCode == 32 ) {
return false;
}
});
}
you used event.keycode == 32 in your If statement But, it should capital C in keycode like
event.keyCode == 32
Check for iframe empty content , iframe id = 'if'
if ($('#iframe').contents().find('body').children().length == 0) {
alert('I frame is empty');
if (event.keyCode == 32 || event.keyCode == 13) {
return false;
}
}
Here is how I was able to capture CTRL+C in jQuery
$(window).bind('keydown', function (event) {
if (event.ctrlKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 'p':
event.preventDefault();
printFunc();
break;
}
}
});
How can i do the same for ALT+F+P
$(window).bind('keydown', function (event) {
if (event.altKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 'f':
event.preventDefault();
//************ Need help for identifying p **************
// alert('Alt-f');
printFunc();
break;
}
}
});
I tried this also but no luck:
if (event.altKey && event.which == 70 && event.which == 80) {
alert('Alt-f-p');
}
This works, but only if you do "p" before "f". In Chrome at least, Alt+F activates a browser function. Live demo (click).
var pressed = {};
$(document).keydown(function(event) {
//event.altKey 70 80
var k = event.keyCode;
if (event.altKey && (k == 70 || k == 80)) {
pressed[k] = true;
console.log(k);
}
if (pressed[70] && pressed[80]) {
console.log('all pressed!');
}
});
$(document).keyup(function() {
pressed = {};
});
Perhaps you would want to adapt it to use something not conflicted?
i have an input box that is for payments, and i want to only allow number like x.xx, of course xxxx.x will work or xxxxx
i have the setup pretty much working minus some weird behavior. if the numbers 1 and 2 after the decimal can be 2 digits long (works) but if i press 3-9 then it only allows one of that digit. also 0's to the right of the decimal are being allowed infinitely.
heres what im working with. also i want to only allow the enter button and when its pressed then run a function
$('#money-button-input-box').keydown(function(event) {
var str = $(this).val()
if(str.length >= 1){
var rightHalf = str.split('.')[1];
if(rightHalf >= 3 && event.keyCode != 8 ){
event.preventDefault();
}
}
if( (event.keyCode == 190 || event.keyCode == 110) && str.replace(/[^.]/g, "").length >= 1 ){
event.preventDefault();
}
allowOnlyNumbers(event);
if (event.keyCode == 13) {
if($(this).val() == '')return;
enterPayment($(this));
}
});
and the function
function allowOnlyNumbers(events){
// Allow: backspace, delete, tab, escape, and enter
if ( events.keyCode == 46 || events.keyCode == 8 || events.keyCode == 9 || events.keyCode == 27 || events.keyCode == 13 ||
// allow decimals
events.keyCode == 190 || events.keyCode == 110 ||
// Allow: Ctrl+A
(events.keyCode == 65 && events.ctrlKey === true) ||
// Allow: home, end, left, right
(events.keyCode >= 35 && events.keyCode <= 39)) {
// let it happen, don't do anything
return;
} else {
// Ensure that it is a number and stop the keypress
if (events.shiftKey || (events.keyCode < 48 || events.keyCode > 57) && (events.keyCode < 96 || events.keyCode > 105 )) {
events.preventDefault();
}
}
}
http://jsfiddle.net/Qxtnd/
The problem of decimals is because you are using
rightHalf >= 3
which evaluates the actual number & not it's length, because javascript type-casts it to a number for the comparison. What you want instead is the number of digits, try
rightHalf.toString().length >= 2
Fiddle here http://jsfiddle.net/Qxtnd/1/
Edit
As long as rightHalf is a string you can do:
rightHalf.length >= 2
if rightHalf was a number you would get an exception doing that.
function isNumberKeyUp(event, obj, beforeLength, afterLength) {
var text = document.getElementById(obj).value;
var splitText = text.split('.');
if (splitText.length > 1 && splitText[1].length > afterLength) {
document.getElementById(obj).value = splitText[0] + "." + splitText[1].substring(0,2);
return false;
}
return true;
}
function isNumberKey(event, obj,beforeLength,afterLength) {
var keyCode1 = event.keyCode;
var keyCode = 0;
if (keyCode1 == 0)
keyCode = event.which;
else {
keyCode = keyCode1;
}
if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 13 || keyCode == 27 || keyCode == 127 ) {
var text = document.getElementById(obj).value;
if (keyCode == 46 && keyCode1 == 0) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
if (keyCode == 46) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
var splitText = text.split('.');
if (splitText[0].length >= beforeLength) {
if (keyCode == 46 && text.toString().indexOf(".") == -1) {
return true;
} else if (text.toString().indexOf(".") != -1)
{
return true;
}
return false;
}
}
else {
return GetDefault(event);
}
return true;
}
function GetDefault(event) {
var keyCode = event.keyCode;
if (keyCode == 0)
keyCode = event.which;
if (keyCode == 8 || keyCode == 9 || keyCode == 35 || keyCode == 36 || keyCode == 37 || keyCode == 38 || keyCode == 39 || keyCode == 40 || keyCode == 46 || keyCode == 118) {
return true;
}
return false;
}
Below is the html to call this events
<input type="text" onkeyup="return isNumberKeyUp(event,'txtID',9,2);" onkeypress="return isNumberKey(event,'txtID',9,2);" required="required" id="txtID" maxlength="12" value="1.00" name="txtID">
Here's the FIDDLE
rightHalf.length >= 2
$('#money-button-input-box').keyup(function () {
$(this).val(FormatNumber($(this).val()));
});
function FormatNumber(val){
var split = val.split('.');
if (split.length>1) return OnlyNumbersAllowed(split[0])+'.'+OnlyNumbersAllowed(split[1]);
else return OnlyNumbersAllowed(split[0]);
}
function OnlyNumbersAllowed(val){
return val.replace(/\D/g, '');
}
http://jsfiddle.net/Qxtnd/7/
You could easly put this regex in any function, instead of writing what you have now.
im using javascript to validate keys in textbox. it is not working :(
function numeric(e) {
return ((e.keyCode == 8) ||
(e.keyCode == 9) ||
(e.keyCode > 47 && e.keyCode < 58) ||
(e.keyCode > 36 && e.keyCode < 41) ||
(e.keyCode == 46) ||
(e.keyCode > 95 && e.keyCode < 106) ||
e.keyCode == 190 ||
e.keyCode == 110);
}
help me...
function numeric(e) {
e = e || window.event;
keycode = e.keyCode || e.which;
if(keycode === 13){
alert("cheese");
}
}
I know that in I.E. you can set event.keyCode=0 to suppress the key appearing in the control. But I think you need to trap the onkeydown. Firefox might have an equivalent. This is good because it prevents the key actually "arriving" at the control.
Also keep in mind that you might need to handle combinations of Shift + key and alt + key.
a good debug technique for this sort of thing is to say windows.status = event.keyCode,
and you can see what the keycode is as you type it...
Just try out the following code. I have checked F5 keycode, you can check as you want
function disableKey(event)
{
if (!event) event = window.event;
if (!event) return;
var keyCode = event.keyCode ? event.keyCode : event.charCode;
if (keyCode == 116) {
showMsg("This functionality is disabled.");
window.status = "F5 key detected! Attempting to disabling default response.";
window.setTimeout("window.status='';", 2000);
// Standard DOM (Mozilla):
if (event.preventDefault) event.preventDefault();
//IE (exclude Opera with !event.preventDefault):
if (document.all && event && !event.preventDefault) {
event.cancelBubble = true;
event.returnValue = false;
event.keyCode = 0;
}
return false;
}
}
function setEventListenerForFrame(eventListener)
{
document.getElementById('your_textbox').onkeydown = eventListener;
//frames['frame'].document.onkeypress = eventListener;
}
<body onload="setEventListener(disableKey);">
Try this if you want a numbers only textbox:
function numbercheck(event) {
var unicode = event.charCode; var unicode1 = event.keyCode; if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1) {
if (unicode1 != 8) {
if ((unicode >= 48 && unicode <= 57) || unicode1 == 37 || unicode1 == 39 || unicode1 == 35 || unicode1 == 36 || unicode1 == 9 || unicode1 == 46)
{ return true; }
else
{ return false; }
}
}
if (navigator.userAgent.indexOf("MSIE") != -1 || navigator.userAgent.indexOf("Opera") == -1) {
if (unicode1 != 8) {
if (unicode1 >= 48 && unicode1 <= 57)
{ return true; }
else
{ return false; }
}
}
}
And in your textbox call it on the onkeypress event:
onkeypress="return numbercheck(event)"