Catching TAB key press with keyup - javascript

I need to archieve 2 objectives but I archive one at time, never both of them.
First I have an input field that should fires an event when a key is pressed and I need to catch the field value. I use letters, number and the TAB key. So if I use keyup it fires at the first char. If I use keydown it takes 2 char to fire because when it fires the first time the char is not pressed yet. So when I press for the second time it fires with the first letter and so on.
Said that, it is clear that what I need is the keyup event that put the value in the field then the event is fired. But TAB has a special meaning in my case and it is not the default behavior and with TAB key I am unable to catch e.which, e.charCode nor e.keyCode! Only with keydown I am able to get those value!
Now I don´t have a clue what to do. How could I catch TAB key or make keydown catch the value of a field?
P.S keypress also working as keydown. Event is fired before I have the value in the field
EDIT 1:
Here is the code:
$('input[data-action="keyupNome"]').each(function () {
$(this).on("keypress", function(e) {
//Se o campo não estiver vazio
if($(this).val() != '') {
if(key != 9) // the tab key code
{
limpaCamposBusca('nome');
var width = $('#nomeBusca').width();
$('.nomeContainer').css('width', width);
$('.displayNomeTbl').css('width', width);
buscaEndereco('Controller/Dispatcher.php?classe=Buscas&acao=buscaEnderecoPorNome', 'nome');
}//if key == 9
else {
alert('here');
e.preventDefault();
}
}// val == ''
else {
clearFields();
clearBuscaCliente();
reactivateFields();
}
});
});

The trick is to use keydown and to combine actual value of the field with the char currently pressed OR to catch TAB in keydown and set an external variable to be used in keyup as in my example.
EDIT :
In fact, I realized that not preventing default behavior of TAB in keydown doesn't fire keyup. So, no variable is needed, but only preventing TAB on keydown. Anyhow, this version always work if the glitch you talked about exist in some circumstances.
(function() {
var tabKeyPressed = false;
$("#t").keydown(function(e) {
tabKeyPressed = e.keyCode == 9;
if (tabKeyPressed) {
e.preventDefault();
return;
}
});
$("#t").keyup(function(e) {
if (tabKeyPressed) {
$(this).val("TAB"); // Do stuff for TAB
e.preventDefault();
return;
}
//Do other stuff when not TAB
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="t" value="">

Related

How to trigger a button click on key press

<input type = “reset” onclick=‘outputx()’>
I want to trigger the button without me clicking on it when the d key is pressed. Output the function and reset at the same time.
You add an event listener to the window. The ASCII code for the letter d is 68.
window.addEventListener("keydown", onKeyDown, true);
function onKeyDown(e){
if(e.keyCode == 68){
outputx();
}
}
First, you have smart quotes “” instead of straight quotes (""). Never use formatted text when coding.
Next, just set up a keydown event handler on the document that checks to see if the d key was pressed:
function output(){
console.log("You did it!");
}
document.addEventListener("keydown", function(event){
if(event.key === "d"){
document.querySelector("input[type='reset']").click();
}
});
<input type = "reset" onclick="output()">

Triggered keypress events not being captured?

I'm capturing input from a barcode scanner (which acts like keyboard input) and it works great, but I don't have access to a barcode scanner at the moment and need to test my code, so I need to simulate the barcode scanner (keyboard) input.
I thought triggering keypress events for each character would work, but it doesn't. Here's my test code:
var barcodeScannerTimer;
var barcodeString = '';
// capture barcode scanner input
$('body').on('keypress', function (e) {
barcodeString = barcodeString + String.fromCharCode(e.charCode);
clearTimeout(barcodeScannerTimer);
barcodeScannerTimer = setTimeout(function () {
processBarcode();
}, 300);
});
function processBarcode() {
console.log('inside processBarcode with barcodeString "' + barcodeString + '"');
if (!isNaN(barcodeString) && barcodeString != '') { // #todo this check is lame. improve.
alert('ready to process barcode: ' + barcodeString);
} else {
alert('barcode is invalid: ' + barcodeString);
}
barcodeString = ''; // reset
}
window.simulateBarcodeScan = function() {
// simulate a barcode being scanned
var barcode = '9781623411435';
for (var i = 0; i < barcode.length; i++) {
var e = jQuery.Event("keypress");
e.which = barcode[i].charCodeAt(0);
$("body").focus().trigger(e);
}
}
JSFIDDLE
If you type in a number quickly (like 1234), you'll see the input is captured fine. However, click the button to run my test code, and the input is not captured. The event is triggered because an alert box pops up, but barcodeString is empty!
Why isn't this working? Should I be triggering some event other than keypress?
The handler is reading the charCode but you are only setting which on the event. Set charCode, or read from which. https://jsfiddle.net/mendesjuan/bzfeuezv/1/
barcodeString = barcodeString + String.fromCharCode(e.which);
Firing Synthetic events
This is a reminder that firing synthetic events is tricky business and typically requires you to have intimate knowledge of the handlers (which is bad) so that you don't have to construct a full event object. Also, beware that not all events triggered by jQuery will actually trigger the native events and cause its default action to apply.
Simply put, triggering keypress does not actually type a character into a text field or fires event handlers not set with jQuery.
document.querySelector('input').addEventListener('keypress', function() {
console.log('standard input key press handler');
});
var e = jQuery.Event("keypress");
e.which = "a".charCodeAt(0);
$('input').keypress(function(){
console.log('jQuery input key press handler');
}).trigger('keypress', e);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="yo" />

how to call jquery autocomplete function on ctrl+ spacebar?

How can I call a javascript function on CTRL + Space?
function getdata() {
console.log("hello");
}
When I hit the getdata() function on CTRL + Space and gives me autosuggestion.
If user type something on my textbox like sta
User types CTRL + Space
It should give me a auto suggestions like stack, stackover, stackoverflow
In order to accept the keyboard input from CTRL + SPACE you'll need to register an event handler (http://www.quirksmode.org/js/events_tradmod.html) and then listen out for input from the user. This will read from an array of keystroke events and check whether they're true, then fire event when keys have been pressed, when they get released the events are false.
var map = {17: false, 32: false};
$(document).keydown(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = true;
if (map[17] && map[32]) {
// FIRE EVENT
}
}
}).keyup(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = false;
}
});
if you go to this link: cambiaresearch.com/articles/15/javascript-char-codes-key-codes, you'll find that the keycodes are all listed here. 17 and 32 is CTRL + SPACE.
check out this guide on auto_complete with JQuery. This code will be executed where the event is fired.
https://github.com/mliebelt/jquery-autocomplete-inner
Look at this answer. - https://stackoverflow.com/a/16006607/2277126
Here you have list of key codes key codes
Good luck!
Here's how I got JQuery autocomplete to show its dropdown list when the user presses Ctrl + space:
$( "#" + myElementId )
.on( "keydown", function( event ) {
// Ctrl+space opens the autocomplete dropdown
if (event.keyCode === $.ui.keyCode.SPACE && event.ctrlKey ) {
$(this).autocomplete("search");
}
});

Need to evoke an enter keypress on textarea?

I have this obfuscated webpage that contains a text-area,
When a user manually inserts text and presses Enter key while editing the text area an event that changes the DOM launches.
I need to pragmatically launch that event,
I know how to get to the text-area itself (using getElementsByName)
and I'm basically inserting text via textArea.value = ''
How do I get that event to launch?
Could you call a function when enter is pressed, and then also just call that function when you want to simulate enter being pressed?
element.addEventListener("keypress", function(event){
if (event.keyCode == 13) {
// Enter has just been pressed.
enterPressed();
}
});
function enterPressed(){
// Do whatever you do when enter is pressed.
}
// Somewhere else off in your code when you want to "trigger" the enter press event:
enterPressed();
is this what you want
document.getElementById("id_of_your_textarea").addEventListener("keydown", function(e) {
if (!e) { var e = window.event; }
e.preventDefault(); // sometimes useful
// Enter is pressed
if (e.keyCode == 13) { document.getElementById("id_of_your_textarea").value = '' }
}, false);
EDIT: based on your comment, you can use the trigger
if you can use jQuery.
$('#textArea').trigger('keydown');

Disabling enter key for form

I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The code is in my head section and seems to be correct from other sources.
disableEnterKey: function disableEnterKey(e){
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
},
if you use jQuery, its quite simple. Here you go
$(document).keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
}
});
Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:
<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>
This code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".
Here are some highlights:
It is in pure javascript (no library required).
Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
Together with the above, user can use "Enter" key anywhere else.
It is short, clean, fast and straight to the point.
If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...
In your form tag just paste this:
onkeypress="return event.keyCode != 13;"
Example
<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">
This can be useful if you want to do search when typing and ignoring ENTER.
/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
For a non-javascript solution, try putting a <button disabled>Submit</button> into your form, positioned before any other submit buttons/inputs. I suggest immediately after the <form> opening tag (and using CSS to hide it, accesskey='-1' to get it out of the tab sequence, etc)
AFAICT, user agents look for the first submit button when ENTER is hit in an input, and if that button is disabled will then stop looking for another.
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)
https://www.w3.org/TR/html5/forms.html#implicit-submission
However, I do know that Safari 10 MacOS misbehaves here, submitting the form even if the default button is disabled.
So, if you can assume javascript, insert <button onclick="return false;">Submit</button> instead. On ENTER, the onclick handler will get called, and since it returns false the submission process stops. Browsers I've tested this with won't even do the browser-validation thing (focussing the first invalid form control, displaying an error message, etc).
The solution is so simple:
Replace type "Submit" with button
<input type="button" value="Submit" onclick="this.form.submit()" />
this is in pure javascript
document.addEventListener('keypress', function (e) {
if (e.keyCode === 13 || e.which === 13) {
e.preventDefault();
return false;
}
});
Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:
//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
if (e.which == 13) e.preventDefault();
});
Thanks to this answer: https://stackoverflow.com/a/1977126/560114.
Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.
<script type="text/javascript">
function stopEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
document.onkeypress = stopEnterKey;
</script>
You can try something like this, if you use jQuery.
$("form").bind("keydown", function(e) {
if (e.keyCode === 13) return false;
});
That will wait for a keydown, if it is Enter, it will do nothing.
I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form.
You need to attach disableAllInputs to onload of the page or via jquery ready()
/*
* Prevents default behavior of pushing enter button. This method doesn't work,
* if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
* the input. So method should be attached directly to the input 'onkeydown'
*/
function preventEnterKey(e) {
// W3C (Chrome|FF) || IE
e = e || window.event;
var keycode = e.which || e.keyCode;
if (keycode == 13) { // Key code of enter button
// Cancel default action
if (e.preventDefault) { // W3C
e.preventDefault();
} else { // IE
e.returnValue = false;
}
// Cancel visible action
if (e.stopPropagation) { // W3C
e.stopPropagation();
} else { // IE
e.cancelBubble = true;
}
// We don't need anything else
return false;
}
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
try {
var els = document.getElementsByTagName('input');
if (els) {
for ( var i = 0; i < els.length; i++) {
els[i].onkeydown = preventEnterKey;
}
}
} catch (e) {
}
}
I think setting a class to a form is much better. so I coded that:
HTML
<form class="submit-disabled">
JS
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('submit', function (e) {
e.preventDefault()
});
/**
* </End>
* Submit Disabled Form
*/
And also if you want to disable submitting only when Enter Key press:
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('keypress', function (e) {
if (e.keyCode === 13) {
e.preventDefault()
}
});
/**
* </End>
* Submit Disabled Form
*/
in HTML file:
#keypress="disableEnterKey($event)"
in js file:
disableEnterKey(e) {
if (e.keyCode === 13) {
e.preventDefault();
}
}
First you need to disable the form on submit, but re-enable it when clicked on the button. which or keycode is not used in this case, avoiding some problems with compatibility.
let formExample = document.getElementbyId("formExample");//selects the form
formExample.addEventListener("submit", function(event){ //must be used "submit"
event.preventDefault();// prevents "form" from being sent
})
To reactivate and submit the form by clicking the button:
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateButton); //calls the function "activateButton()" on click
function activateButton(){
formExample.submit(); //submits the form
}
a variation of this would be
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateBtnConditions); //calls the function "activateBtnConditions()" on click
function activateBtnConditions(){
if(condition){
instruction
}
else{
formExample.submit()
}
}
Here is a modern, simple and reactive solution which works in:
React, Solidjs, JSX etc.
is written in Typescript
supports server-side rendering (SSR)
all modern browsers
does NOT require jQuery
blocks ALL Enter keys outside of <textarea> where you want to allow Enter
// avoids accidential form submission, add via event listener
function blockEnterKey(e: KeyboardEvent) {
if (e.key == "Enter" && !(e.target instanceof HTMLTextAreaElement)) {
e.preventDefault()
}
}
// add the event listener before the rendering return in React, etc.
if (typeof window !== undefined) {
window.addEventListener("keydown", blockEnterKey)
// the following line is for Solidjs. React has similar cleanup functionality
// onCleanup(() => document.body.removeEventListener("keydown", blockEnterKey))
}
return(
<form>
...
</form>
)
The better way I found here:
Dream.In.Code
action="javascript: void(0)" or action="return false;" (doesn't work on me)

Categories