Change key by other in keypress event or keydown event - javascript

When my user press "." I need that browser show ",".
I intent use this Extjs code buy don't work :(
Ext.EventManager.on(document, 'keypress', function(evt, t, o) {
if (evt.keyCode == 46) { // .
evt.keyCode = 44; // ,
}
});
Any idea?

You are changing the value of the event, and that's not going to change the value of the resultant string.
You should replace the . for the ,on the string ater you catch the event:
Ext.EventManager.on(document, 'keypress', function(evt, t, o) {
if (evt.keyCode == 46) { // .
resultantString.replace('.', ',');
}
});

Obviously, this won't work, because you are merely changing the keyCode. That won't somehow reflect on the screen. You will have to locate the element that caused the event and set its text to (whatever was before) + (remove the .) + (,)
Of course, this is the long way out. I hope someone has a shorter way.

Related

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");
}
});

javascript how to detect keyboard input

when focusing on a certain input,
user press kind of combination key such as "ctrl+e",
I would like to show "ctrl+e" in the input.
next time user press another combination key,
it will clean input and show the new one.
how can I make this?
I look for some javascript plugins,
but they are most for detecting certain input.
like this:
https://github.com/OscarGodson/jKey
$("input").jkey("i",function(){
jkey.log("You pressed the i key inside of an input.");
});
thanks a lot.
Another approach (no plugin needed) it to just use .ctrlKey property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:
$(document).keypress("c",function(e) {
if(e.ctrlKey)
alert("Ctrl+C was pressed!!");
});
Update
$(document).on('keypress','input',function(e){
if ( e.ctrlKey && ( String.fromCharCode(e.which) === 'c' || String.fromCharCode(e.which) === 'C' ) ) {
console.log( "You pressed CTRL + C" );
}
});
Not all browsers allow the catching of cntrl keypress. This would work for the rest
$( document ).keypress(function(e) {
var ch = String.fromCharCode(e.charCode);
if(e.ctrlKey){
console.log('cntrl+'+ch+' was pressed');
}else{
console.log(ch+' was pressed');
}
});

Mirroring input content with non-printable chars like CTRL, ALT or shift key

When non-printable char is pressed, it's replaced with let's say for CTRL=17 with "[CTRL]".
Here is code an example
$('#textbox1').keyup(function (event) {
if (8 != event.keyCode) {
if(17==event.keyCode){
$('#textbox1').val($('#textbox1').val()+"[CTRL]")
$('#textbox2').val($('#textbox1').val());
}else{
$('#textbox2').val($('#textbox1').val());
}
} else {
$('#textbox2').val($('#textbox1').val());
}
});
the problem is when user presses backspace the second input must reflect the content of the first one, so "[CTRL]" must be deleted at once like any other chars.
You could make use of the keyCode and/or in combination with charCode (if required). Basic idea would be:
Create a map of all required key codes in an array/object
Handle event for say keydown and listen for keycode
Look for the keycode in your map and if found show it
prevent the default (to prevent e.g. say backspace browsing back)
If not found in map, let the character go thru as usual.
A very basic example:
Demo: http://jsfiddle.net/abhitalks/L7nhZ/
Relevant js:
keyMap = {8:"[Backspace]",9:"[Tab]",13:"[Enter]",16:"[Shift]",17:"[Ctrl]",18:"[Alt]",19:"[Break]",20:"[Caps Lock]",27:"[Esc]",32:"[Space]",33:"[Page Up]",34:"[Page Down]",35:"[End]",36:"[Home]",37:"[Left]",38:"[Up]",39:"[Right]",40:"[Down]",45:"[Insert]",46:"[Delete]"};
$("#txt").on("keydown", function(e) {
// check if the keycode is in the map that what you want
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
// if found add the corresponding description to the existing text
this.value += keyMap[e.keyCode];
// prevent the default behavior
e.preventDefault();
}
// if not found, let the entered character go thru as is
});
Edit: (as per the comments)
The concept remains the same, just copying the value to the second input:
Demo 2: http://jsfiddle.net/abhitalks/L7nhZ/3/
$("#txt1").on("keyup", function(e) {
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
this.value += keyMap[e.keyCode];
e.preventDefault();
}
$("#txt2").val(this.value); // copy the value to the second input
});
Regarding deletion of the description, I could not get it done by caching the last inserted descrition from the map. Somehow, I kept struggling with the regex with a variable. Anyway, a simpler solution is to just add another event handler for keyup with hard-coded map.
Thanks to #serakfalcon for (that simple solution), which we are using here:
$('#txt1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(Tab|Enter|Shift|Ctrl|Alt|Break|Caps Lock|Esc|Space|Page (Up|Down)|End|Home|Left|Up|Right|Down|Insert|Delete)\]$/,' '));
$("#txt2").val(el.val());
}
});
You can check in the keydown for the last character in the input field. If it's a ] you can remove everything from the right to the last found opening bracket [. Unfortunatly this does not work if you're cursor is inside '[ ]'.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var element = $(this),
value = element.val(),
lastChar = value.slice(-1);
if(lastChar == ']') {
var lastIndex = value.lastIndexOf('['),
index = value.length - lastIndex;
element.val(value.slice(0, -index) + "]");
}
}
});
Fiddle
you can always use a regex.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(CTRL|ALT|SHIFT)\]$/,' '));
}
});
fiddle
Edit: combined with abhitalks code

Remove Any Spaces While Typing into a Textbox on a Web Page Part II

This involves HTML + JS and/or JQuery:
I would have commented on the previous post, but I don't have comment reputation or cannot comment for some reason.
Josh Stodola's great code from Part I is as follows:
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
This works great except .replace puts the cursor at the end of the string on every keyup (at least in IE8 and Chrome).
As a result, it renders the left & right cursor keys useless, which is needed inside the input box.
Is there any way to enhance the above code so that the cursor keys do not activate it, but so that the text still gets updated on the fly?
The best solution is to avoid using key events to capture text input. They're not the best tool for the job. Instead, you should use the HTML5 oninput event (supported in the latest and recent versions of every current major browser) and fall back to onpropertychange for older versions of Internet Explorer:
var alreadyHandled;
txt.bind("input propertychange", function (evt) {
// return if the value hasn't changed or we've already handled oninput
if (evt.type == "propertychange" && (window.event.propertyName != "value"
|| alreadyHandled)) {
alreadyHandled = false;
return;
}
alreadyHandled = true;
// Your code here
});
These events don't fire for keys that don't result in text entry — don't you just hate it when you shift-tab back to a form element and the resulting keyup event causes the page's script to move focus forward again?
Additional benefits over key events:
They fire immediately when the key is pressed and not when the key is lifted, as in keyup. This means you don't get a visual delay before any adjustments to the text are made.
They capture other forms of text input like dragging & droppping, spell checker corrections and cut/pasting.
Further reading at Effectively detecting user input in JavaScript.
Update the function:
var func = function(e) {
if(e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40){
txt.val(txt.val().replace(/\s/g, ''));
}
}
try:
$(function() {
var txt = $("#myTextbox");
var func = function(e) {
if(e.keyCode != "37" && e.keyCode != "38" && e.keyCode != "39" && e.keyCode != "40"){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(function(evt){
if(evt.keyCode < 37 || evt.keyCode > 40) {
func;
}
}).blur(func);
});
Something like that should do it. It will run the function if the keycode isn't 37,38,39 or 40 (the four arrow key keycodes). Note that it won't actually stop the cursor position moving to the end when any other key is pressed. For that, you'd need to keep track of the current cursor position. Take a look at this link for jCaret plugin, which can do this

Combination of Keypresses using JS / jQuery ( Escape & Shift +Escape )

Is there a way in js/jQuery how to have these two combinations of keypresses?
ESCape key
and
SHIFT + ESCape key
when I implemented it using:
document.onkeydown = function(e){if (e == null) {keycode = event.keyCode;}
else {keycode = e.which;}
if(keycode == 27){closeAll();}}
//upon pressing shift + esc
$(document).bind('keypress',function(event)
{
if(event.which === 27 && event.shiftKey)
{
closetogether();
}
});
The escape button works perfectly but the one with the shift + esc is getting confused I think because it's doing nothing. Don't worry the function works as when I change the combining key 27 to 90 (z) for example it works just fine.
Can someone opt me for a better way ?
Why don't you bind the keydown event using jQuery? That way you would already have a normalized event variable. You can also check the status of the shift key in the same handler.
These events send different keycodes back. Use keyup/keydown for capturing certain keys by scancodes and use keypress to capture actual text input by characters.
$(document).bind('keydown', function(event) {
if(event.which === 27){
if(event.shiftKey){
closetogether();
} else {
closeAll();
}
}
});

Categories