How do i simulate enter key pressed to behave like tab. I would not like to use jQuery. I simply need to blur(loose focus) on current input (textfield) and focus on next (input) element. I tried this but it doesn´t work.
const handleKeyUp = (event) => {
const keyCode = event.keyCode || event.which;
if (event.target.value !== '' && keyCode === 13) {
event.preventDefault();
event.target.blur();
event.target.dispatchEvent(new KeyboardEvent('keypress', { key: 'Tab' }));
}
};
You can't trigger default browser behaviour by simulating events.
You'll need to identify the next field in the tab order, find it in the DOM, then call its focus() method.
$(document).on('keydown', ':tabbable', function (e) {
if (e.which == 13 || e.keyCode == 13 ) {
e.preventDefault();
var $canfocus = $(':tabbable:visible')
var index = $canfocus.index(document.activeElement) + 1;
if (index >= $canfocus.length) index = 0;
$canfocus.eq(index).focus();
}
});
Example
Related
I need to track the click on capslock and then the keyboard shortcut ctrl + alt, that is, first click on capslock and then on the keyboard shortcut here is an example
if (e.code == "CapsLock") {
if (e.ctrlKey && e.keyCode == 18) {
alert();
}
}
but this code does not work
I use a function like this:
document.addEventListener("keydown", function (e) {
var caps = e.getModifierState && e.getModifierState('CapsLock'); // true if pressed, false if released
document.onkeyup = function(event) {
if(caps === true){
/** Validate keys are to be processed */
var keycode = event.which;
// works off course only if ctrl key is kept pressed during key stroke = normal behavior in most OS
// Should it work like a ctrl-Lock function you have to work with a state variable
if ((event.ctrlKey === true) && (keycode === 18)) {
alert();
}
else{
/** Let it happen, don't do anything */
return;
}
}
};
});
I want to use shortcut to handle a task in Javascript (not JQuery or any Javascript libraries). For example, I want to use Ctrl+Q to write an alert. My issue is only to use Ctrl+Q, combination of other keys such as Ctrl+Q+other key will not handle the alert. How can I do?
document.addEventListener('keydown', function(event){
if(event.ctrlKey && event.keyCode == 81) console.log('alert');
});
I only want Ctrl+Q work, not for Ctrl+Shift+Q, Ctrl+Alt+Q, Ctrl+Q+(some key else)
Just ensure none of the other three modifiers are pressed:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.keyCode == 81 && !(event.shiftKey || event.altKey || event.metaKey)) console.log("alert");
});
The code below should solve your problem(Updated Code):
document.addEventListener("keydown", function (event) {
var map = [];
onkeyup = function(e){
map.push(e.key);
console.log(map);
if(map.length == 2){
console.log("CTRL + Q was pressed",map.indexOf("q") > -1 && map.indexOf("Control") > -1)
}
onkeydown = function(e){
// console.log(map);
}
}
});
If any other button is pressed along with ctrl (For instance: ctrl+shift+Q or ctrl+alt+q), it returns false!! Let me know if that solves your problem. Cheers!!
You'll need to keep track of what keys are pressed with keydown and which keys are released with keyup, then, when a new key is pressed, you would check for only Ctrl and Q currently being down.
Something like this should work:
var keysPressed = [];
function onPressOrRelease(event) {
if (event.type === "keydown") {
if (!keysPressed.includes(event.keyCode))
keysPressed.push(event.keyCode)
} else if (event.type === "keyup")
keysPressed.splice(keysPressed.indexOf(event.keyCode), 1);
let ctrlQPressed = keysPressed.includes(81) && keysPressed.includes(17) && !keysPressed.some(a => a !== 81 && a !== 17)
if (ctrlQPressed)
console.log("pressed");
}
document.addEventListener("keydown", onPressOrRelease);
document.addEventListener("keyup", onPressOrRelease);
You'll want to make sure keys don't get added multiple times and may want to clear the array on focus loss (since using control it may lose focus when releasing)
function animatedForm() {
const arrows = document.querySelectorAll(".fa-arrow-down");
arrows.forEach(arrow => {
arrow.addEventListener("click", () => {
const input = arrow.previousElementSibling;
const parent = arrow.parentElement;
const nextForm = parent.nextElementSibling;
//Validation
if (input.type === "text" && validateUser(input)) {
nextStep(parent, nextForm);
} else if (input.type === "email" && validateEmail(input)) {
nextStep(parent, nextForm);
} else if (input.type === "password" && validatePassword(input)) {
nextStep(parent, nextForm);
}
});
});
};
function nextStep(parent, nextForm) {
parent.classList.add("inactive");
parent.classList.remove("active");
nextForm.classList.add("active"); }
function error(color) {
document.body.style.background = color; }
animatedForm();
If you want to run some code when enter button pressed, listen to 'keydown' event on document element and check event.key in listener. Your code should be something like that:
document.addEventListener('keydown', e => {
if(e.key === 'Enter') doSomething();
})
To add enter key up event, all you have to do is add a keyup listener and filter on which key was pressed like this :
element.addEventListener('keyup', e => {
// e.key might not be supported, keyCode for backward compatibility
if(e.key && e.key !== "Enter" || e.keyCode !== 13) return
// your code here
}
I add form using jquery append method and this method has .numerik_kontrol class but this functions working are another form but it's not working on my dynamic form
my function;
$(document).ready(function(){
/** numerik kontrol*/
$(".numerik_kontrol").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// 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();
}
});
/** numerik kontrol bitiş*/
/** select seçim*/
$(".btn_ekle").on("click", function(e) {
var ekle = $(".ekle").html();
$(".add_after").append(ekle).show();
e.preventDefault();
});
$(document).on('change', '.havale_tipi', function() {
var value = $(this).val(),
parent = $(this).closest(".group");
if (value == "iban_no") {
$(".hesaba_form", parent).fadeOut();
$(".iban_no_form", parent).fadeIn();
} else {
$(".iban_no_form", parent).fadeOut();
$(".hesaba_form", parent).fadeIn();
}
});
$(document).on("click", ".iade_sil", function() {
var form_sil;
var form_sil = confirm("Formu silmek istediğinize emin misiniz ?");
if (form_sil == true) {
$(this).closest(".group").remove();
} else {
return false;
}
});
document.getElementById('iade_miktari').className="numerik_kontrol";
});
if you wanna check out full click this link - demo page
if you click bottom of the form button(left button) you gonna see dynamic forms
In your $(document).ready use a $(document).on event handler instead of a keydown handler on existing numerik_kontrol elements. This will bind the handler to the document and evaluate the selector when every keydown event occurs, instead of directly binding the handler to the result of the single selector evaluation in $(document).ready
i.e.
instead of:
$(".numerik_kontrol"),keydown(function(e) { ...
try something more like this:
$document.on("keydown", ".numerik_kontrol", function(e) { ...
How to do that?
I tried:
var key = event.which || event.keyCode || event.charCode;
if(key == 8) alert('backspace');
but it doesn't work...
If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the typed character in my input field. I need to be able to control that
my code:
$('#content').bind('input', function(event){
var text = $(this).val(),
key = event.which || event.keyCode || event.charCode;
if(key == 8){
// here I want to ignore backspace and del
}
// here I'm doing my stuff
var new_text = 'bla bla'+text;
$(this).val(new_text);
});
no character should be appended in my input, besides what I'm adding with val()
actually the input from the user should be completely ignored, only the key pressing action is important to me
Use .onkeydown and cancel the removing with return false;. Like this:
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
};
Or with jQuery, because you added a jQuery tag to your question:
jQuery(function($) {
var input = $('#myInput');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
});
});
event.key === "Backspace"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Mozilla Docs
Supported Browsers
With jQuery
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
http://api.jquery.com/event.which/
jQuery('#input').on('keydown', function(e) {
if( e.which == 8 || e.which == 46 ) return false;
});
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
keydown with event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Modern style:
input.addEventListener('keydown', ({key}) => {
if (["Backspace", "Delete"].includes(key)) {
return false
}
})
Mozilla Docs
Supported Browsers
Have you tried using 'onkeydown'?
This is the event you are looking for.
It operates before the input is inserted and allows you to cancel char input.
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
return false;
}
});
InputEvent.inputType can be used for Backspace detection Mozilla Docs.
It works on Chrome desktop, Chrome Android and Safari iOS.
<input type="text" id="test" />
<script>
document.getElementById("test").addEventListener('input', (event) => {
console.log(event.inputType);
// Typing of any character event.inputType = 'insertText'
// Backspace button event.inputType = 'deleteContentBackward'
// Delete button event.inputType = 'deleteContentForward'
})
</script>
on android devices using chrome we can't detect a backspace.
You can use workaround for it:
var oldInput = '',
newInput = '';
$("#ID").keyup(function () {
newInput = $('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
//Here's one example, not sure what your application is but here is a relevant and likely application
function addDashesOnKeyUp()
{
var tb = document.getElementById("tb1");
var key = event.which || event.keyCode || event.charCode;
if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) )
{
tb.value += "-"
}
}
Live demo
Javascript
<br>
<input id="input">
<br>
or
<br>
jquery
<br>
<input id="inpu">
<script type="text/javascript">
var myinput = document.getElementById('input');
input.onkeydown = function() {
if (event.keyCode == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.keyCode == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
};
//jquery code
$('#inpu').on('keydown', function(e) {
if (event.which == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.which == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
});
</script>