Intercepting keyboard presses - javascript

I have an input box that always has focus. The commands that go into this input box are always letters. If the user presses a number, I would like it not to be added to the text box, but instead use it to run a different command (just like a hotkey).
The way I've seen this implemented is by looking at the keyup event and removing unwanted characters. Instead, is there any way to to intercept the keyboard input and check what the value is before the insert?
I've thought about creating a custom input field using a div and intercepting all the keyboard commands. Is there a way to get a blinking caret so that it looks like an input box?

Sounds like you want a contenteditable div:
<div id="editor" contenteditable="true"></div>
You can listen for keydown events and prevent them if they aren't letters:
$("#editor").keydown(function (e) {
if (e.which > 90 || (e.which > 48 && e.which < 65)) {
e.preventDefault();
}
});
To process the numbers as "hotkeys" you would just determine which key e.which is and act accordingly.
Example: http://jsfiddle.net/g3mgR/1

Something like this will work:
<input type="text" id="txt" />​
For jQuery:
$('#txt').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
if (key > 46 && key < 58) {
event.preventDefault();
alert('its a number, do something');
}
});​
Here is the Fiddle

Use keydown instead of keyup.

Use the keypress event in combination with String.fromCharCode:
document.getElementById('yourTextBoxID').onkeypress = function () {
var characterPressed = String.fromCharCode(event.keyCode);
if (characterPressed.test(/[a-z]/i)) {
// user pressed a letter
} else {
// user did not press a letter
}
};​
http://jsfiddle.net/TSB9r/3/

Related

Is there a way to make Enter and Shift + Enter work the same way in TinyMCE?

I'm using tinymce-react package in my current project. Is there a way to make "enter" and "shift + enter" work the same way? In my case I need them both to insert <p></p> when pressed. I tried different variations of force_root_block, force_p_newlines and force_br_newlines but it always ends up that one of them insert <p></p> and the other one <br/>. Thanks in advance for help :)
Are you looking for something like this?
//target textarea with querySelector
var textA = document.querySelector("textarea");
textA.addEventListener("keyup", function(event) {
// keyCode 13 is the "Enter" key on the keyboard
// keyCode 16 is the "Shift" key on the keyboard
if (event.keyCode === 13 || event.keyCode === 16) {
// Prevent default action
event.preventDefault();
//if shift or enter are pressed then insert new paragraph
textA.value = textA.value + "<p></p>"
}
});
<textarea></textarea>

How to fire the actual "Enter" keypress event of the browser?

I know it is possible to use JQuery.Event to simulate "Enter" keypress. Something like this does that -
var event = jQuery.Event( "keydown" );
event.keyCode = 13
$("input").trigger( event );
However, this does not fire the browser default behavior when the actual "Enter" key is pressed. For example, going to next line if the cursor is in textarea or submitting the form when the cursor is in input tag.
I want to know if it is possible to trigger or simulate the actual "Enter" keypress event/behavior.
Try this : Js fiddle
var e = jQuery.Event("keypress");
e.which = 13
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
Do you want some thing similar this one?
$(function(){
$(document).keypress(function(event) {
if(event.which == 13) {
console.log("Dude! You hit Enter Key!!");
}
});
});
you can use this:
$("body").delegate("input", "keypress",function(e){
if(e.which == 13){
}
}
it's work for all input .

How to prevent form submission using the keyboard (esp. the space key)

I have a web application where on one specific screen I have to make sure the user clicked the button using the mouse as opposed to just pressing enter or space.
I have written this code:
$('button').keydown(function (e) {
if (e.which === 10 || e.which === 13 || e.which === 32) {
return false;
}
});
However, this only works for enter. The form can still be submitted by pressing space on a button. I am just wondering what caused this inconsistency and how to get around it?
Edit:
Example fiddle: http://jsfiddle.net/billccn/3JmtY/1/. Check the second check box and pressing enter while the focus is on the button will have no effect. If I further disable the input and expand the keydown trapping to the whole form, then enter cannot be used to submit the form.
Edit 2:
I do have a backup plan which is replacing the button with a link or even a plain div and use the click event to submit the form programmatically. However, extra work is required to make it look like a button so I'd rather use a button is possible.
Just found out: handling space (32) on keyup will prevent the click event.
Updated fiddle: http://jsfiddle.net/3JmtY/2/
Missed the Point of your Question. After some googleing if found the following trick:
Bind the keypress event to your from and listen to it's keycode. If the keycode is 13
(enter), prevent all default actions (event.preventDefaul()) and prevent further event bubbeling ( return false; ).
Her is a fiddler code example:
HTML:
<form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">Trigger the handler</div>
JavaScript:
$('#target').keypress(function (event) {
var code = event.keyCode || event.which;
if (code == 13) {
event.preventDefault();
return false;
}
});
$('#target').submit(function (event, data2) {
debugger;
alert('test');
return false;
});
Fiddler: http://jsfiddle.net/ggTDs/
Note that the form is not submited when enter is clicked!
Use below code. 13 for Enter key and 32 for Spacebar.
$("#form_id").on('keydown keyup keypress', function( e ) {
if ( e.keyCode == 13 || e.which == 13 || e.which == 32 ) {
e.preventDefault();
return false;
}
});

jquery focusin doesn't work when calling .focus() and return false;

I have a problem with the focusin/focusout events of jQuery (1.7.2).
I have 2 inputs in a div. When one of them gains focus, I want to add a class to the div. I only want to remove this class, if none of the inputs has focus anymore.
$(function() {
$('#container').on('focusin',function(){
$(this).addClass('test');
}).on('focusout',function(){
if ($(this).find('input:focus').length) return;
$(this).removeClass('test');
});
$('#container input').on('keydown',function(e) {
var keycode = e.keyCode || e.which;
//When Tab or Return, switch input
if (keycode == 9 || keycode == 13) {
$($(this).attr('data-target')).focus();
return false;
}
});
});
<div id="container">
<input type="text" id="a" data-target="#b">
<input type="text" id="b" data-target="#a">
</div>
http://jsfiddle.net/pqUFX/
Works fine, when I click into the inputs with my mouse to switch the focus. But when setting the focus to the other input inside the keydown() event of the input by calling $('#b').focus(); the class gets removed, even when checking for existing focuses inside the div.
Is it perhaps because of my return false;, so the tab doesn't switch twice? Do you have any alternative solution for this?
Not sure why it not works really (it should) but why don't you use something like this:
$(function() {
$('#container input').on('keydown',function(e) {
var keycode = e.keyCode || e.which;
//When Tab or Return, switch input
if (keycode == 9 || keycode == 13) {
$($(this).attr('data-target')).focus();
$(this).parent().addClass("test");
return false;
}
}).focusin(function() {
$(this).parent().addClass("test");
}).focusout(function() {
$(this).parent().removeClass("test");
});
});​

jQuery how to figure out if user inputed ' ' in text input area?

we have an input type="text" user prints into it some string. each time he inputs empty space char we want to call some function. How to do such thing with jQuery?
$(input).keydown(function (e) {
if ( e.which === 32 ) {
// do your thing
}
});
where input is a reference to your INPUT element.
Live demo: http://jsfiddle.net/uHpLg/
Check out jQuery's keypress event:
$("#YourInputId").keypress(function() {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 32) { // 32 = space keycode
//Do something
}
});
Here's a web page that has a list of javascript key codes.
Bind a listener to the input onchange event.
Compare the current value to the last value and check is the new character is a space
If so, call a function.
you can select the input text box and bind to it a change listener
but this will work only when the box is unfocused and the new value is different than the old value
$(document).ready(function () {
$('#mytextbox').change(function(){
if ($(this).val() == ' ')
{
// do whatever u want
}
});
});
but if u wanted something like autosuggestion (don't wait for user to unfocus the text input ) u can create ur own listener
is when the user focus the text box ,key press u check the pressed key and if it's is = " " do whatever u want
and when the user unfocus the input , it stops checking it
$('#mytextbox').keypress(function (e){
if (e.keycode == 32 )
{
// do your code here
}
});
for more info about keycodes : http://asquare.net/javascript/tests/KeyCode.html
on keypress Jquery function documentation : http://api.jquery.com/keypress/

Categories

Resources