How can i capture the following keys in Textbox using JavaScript?
Ctl + a
Ctl + c
Ctl + v
Following is the original Situation.
I have three Textboxes for Phones numbers. Textbox1 max length is 3 , 2nd's is 3 and 3rd is 4. When user types three digits in TextBox1 the cursor moves automatically to TextBox2 same thing happens with TextBox2 as well as TextBox3. I am handling this functionality in keyup event. Now, I am parallely using your code. But it moves in keyup event as well. This case happens when all TextBoxes are filled. Now suppose I am in TextBox1 and presses Ctl + A . This moves the user to third TextBox(unacceptable case). This is the issue.
Use the select, copy and paste events respectively. Pretty much universally supported these days.
var textBox = document.getElementById("textBoxId");
textBox.onpaste = function() {
alert("paste");
};
Likewise for the other events. Demo here: http://jsfiddle.net/timdown/EC2Hf/
And what about right click, osx that does not use control, the edit copy option on the browser, the button on my old keyboard, etc?
There is more than just key presses.
That said, most browsers support
oncopy and onpaste events.
You would have to first check if the ctrl button was clicked and then the correspnding letter keys. This link may help you out
Related
I have an input box and want to adjust the value when a key is pressed.
'keypress .comment-input': 'onCommentInputKeyBlur',
When a key is pressed, a class is added to the html element to reflect the changes.
onCommentInputKeyBlur: function(ev) {
var $form = $('#comment-submit');
if (ev.which) {
$form.addClass('focused');
} else if (!$(ev.currentTarget).val()) {
$form.removeClass('focused');
}
},
However, this doesn't detect special keys being pressed (ie when a user presses ctrl+v for a paste, it's not detected and the formatting is therefore wrong).
Using keyup and keydown halfway solve the problem, but formatting is wrong for a brief second:
Keydown -> the value isn't supposed to change until an actual value is entered through a keypress, but it changes right when ctrl is hit instead of waiting for the second key
Keyup -> new value is briefly pasted over the previous one while waiting for the key to actually be released.
Is there a better way to about solving this? Ideally, I would like to detect if the key entered does actually produce a value and is not simply a special key.
Look into the onchange event. It is fairly well supported and may solve your problem.
What is the ultimate goal of this functionality? perhaps there is a better approach.
If you insist on doing this via keypress event, then you can simply check event.keyCode and filter out the few keycodes that dont change anything, such as shift, control, alt.
I'm building a JavaScript game where audio plays and based on the audio you're supposed to type some text into a big textbox. JavaScript is used to score your answer and then clear the textbox to prepare for the next audio clip.
The problem: In some cases when pressing the esc (escape) key while focused within an empty <input type="text" />, the textbox gets populated with some old text.
I'm using MooTools and have tried using event.stop() (which stops propagating and also executes preventDefault) within keypress, keydown, and keyup with no luck.
How can I prevent the [esc] button from changing the value within a textbox?
(This is important because I'm using the [esc] key as a keyboard shortcut to replay the audio)
I was able to fix this by just calling blur() and then focus() on the input box. That cleared the problem in Firefox for me at least.
Interesting problem - it happens in IE for example but not Chrome. Here is a solution I have tested in Chrome and IE (it seems to work).
Expanded version:
Script in page header:
<script>
var buff; //Must have global scope
var input = document.getElementById("testinput"); //Defined here to save cpu (instead of on every key press).
function CheckPreBuff(e)
{
var ev = window.event ? event : e; //Get the event object for IE or FF
var unicode = (typeof(ev.keyCode) != "undefined")? ev.keyCode : ev.charCode;
if(unicode != 27) buff = input.value; //The 'escape' key has a unicode value of 27
else input.value = buff; //Only set the input contents when needed, so not to waste cpu.
}
</script>
Where 'testinput' is the input we are disabling escape on. The testinput html is below:
<input id="testinput" onkeypress="CheckPreBuff();" onkeyup="CheckPreBuff();" type="text"/>
Notice both 'onkeyup' and 'onkeypress' were used - technically only 'onkeyup' is needed, although using 'onkeypress' prevents the text box going blank momentarily whilst the escape key is depressed.
Manually minified + error prevention + multiple inputs supported (if you prefer)
Script in header:
<script>
var buff = [];
function InitCPB(obj){if(typeof(obj)=="undefined")return;buff[0]=obj;buff[1]="";obj.onkeypress=CPB;obj.onkeyup=CPB;}
function CPB(e){if(typeof((buff[0]))=="undefined")return;var ev=window.event?event:e;(((typeof(ev.keyCode)!="undefined")?ev.keyCode:ev.charCode)!=27)?buff[1]=(buff[0]).value:(buff[0]).value=buff[1];}
</script>
testinput html tag (although an id is no longer needed):
<input onfocus="InitCPB(this);" type="text"/>
Both methods keep a copy of what the text inputs contained before the next key was pressed, if the key pressed was 'escape', unicode 27, then the previous text entry was put back into the text box (this is discriminatory so the script does not add too much load to the browser on every key press).
The second version allows for multiple text inputs on the same page having the escape key disabled - just so long as they have the onFocus attribute set as above (the multiple elements will not interfere with each other). It also checks the objects being passes to it are defined, to prevent accidental mis-implementation giving IE a heart attack!
I hope this helps.
When escape detected do what is needed to be done and at the end return false;
It solved the problem in firefox 25 for me.
Here's the problem, in abstract terms: i have three input fields (A, B, C). two of them need to be text inputs (A and B), the third is of irrelevant type. I need to enable the third if A is not empty and B is not empty. I need to disable C if A is empty or B is empty.
The code
// empty is the empty function from the phpjs project
// framework used: jQuery
// A, B and C are classes here
$(".A, .B").keypress(function(){
if( !empty($(".A").val()) && !empty($(".B").val()) )
$(".C").attr("disabled","");
else
$(".C").removeAttr("disabled");
});
I want to be able to check this on keypress, but when requesting the value of the input that is edited when the keypress event occurs i get the value that was calculated before the keypress event.
Has anybody stumbled upon this before and solved it?
have you tried using the keyUp event?
Use the keyup event instead.
Attach your handler to the keyrelease event. The value should have been updated by then.
use a combination of handlers for keyup and change. the keyup handler will update as the user types (excepting edge cases like holding a key down, which doesn't seem like a concern here) and the change handler will catch things like the user cutting the text with mouse actions before they can switch to field C. as an added measure you could add verification on field C's focus event, to make sure A and B really have something.
$('.A, .B').keydown(function(event) {
if(!empty($('.A').val()) && !empty($('.B').val()))
$(".C").attr("disabled","");
else
$(".C").removeAttr("disabled");
});
At the keypress event, the value of the INPUT is not yet set. Hence you can't easily know if it is empty.
While the keyup fires, the value of the INPUT is set.
But things get worse. The user can empty the field with the mouse or the Edit menu of the browser. In that case keyup is not fired.
In our web app we auto-save the values. Like in Mac OS, if you know, there is almost no save buttons.
To allow a reaction here is more or less what we do:
onfocus: a setInterval starts polling every 120ms or so, and checks the input for any change
if there is a change do the relevant action
onblur: a clearInterval stop the polling
is it possible to show/hid a div on a webpage if say three keys are pressed in the correct order on a normal keyboard....
Im trying to hide my login div in drupal and only want it to show if I press say three keys on the keyboard. Dosnt matter if it shows up in source.
any thoughts/links?
cheers
You can try js-hotkeys.
jQuery.Hotkeys plugin lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination. It takes one line of code to bind/unbind a hot key combination.
Example: Binding 'Ctrl+c'
$(document).bind('keydown', 'ctrl+c', fn);
Next step is to show/hide your div in the function you pass in.
You have to intercept the keypress event (or keyup) and then check which key was pressed (see jQuery Event Keypress: Which key was pressed?)
To handle a key sequence you have to store the pressed key codes into an array and then check it against your defined sequence.
This "cheat code" jQuery plugin should make what you're asking especially simple.
If you poll for key presses and store them in array then match that with the correct array once this happens show the div then clear your stored array. Close the div and start the process again.
$("#epFilter").keypress(function(){
query = $("#epFilter").val();
alert(query);
});
In this code, whenever I type in my text box, it always alert one character less. It doesn't catch the last character. Why?
Use the keyup event instead.
$("#epFilter").keyup(function(){
query = $("#epFilter").val();
alert(query);
});
keypress event is triggered when user presses a key, but before the character is inserted. Use keyup event instead.
Slightly improving Matt's answer (using this inside event handler):
$("#epFilter").keyup(function(){
query = $(this).val();
alert(query);
});
I wonder if that is a "normal" behavior. Shouldn't keypress be similar to keydown+keyup (except for the codes and keys)?
I had the same problem. I have an input-text field and I want to calculate a total on keypress. However, it does not change the total until I input again another character (this means when I entered the first digit it didn't update). I used "keyup" and was "fixed", but I think it could be better if I use keypress as it doesn't fire when I press other keys (like Ctrl, Shift, arrows, etc).
According to the documentation Keypress should work as I expected but for some reason it didn't.
This is not exactly an answer (so don't vote for it). Just my contribution.