jQuery keyboard events - javascript

Using jQuery, I would like to capture a keyboard event that is:
before the user lifts their finger from the key
after the characters from the keyboard event have registered in the input box.
To clarify, view this example. When keypress fires, the input value has not been updated yet.
[Edit]
Apparently I wasn't clear as to what I need.
The function must be called before the user lifts their finger up from the key, but after the key's character is placed in the input box. So the following do not work:
keydown: at the keypress event, the value in the text box has not been updated
keypress: at the keypress event, the value in the text box has not been updated
keyup: this is called when the user lifts their finger, which is too late.

You can use the input event, which works in recent versions of all major browsers:
var input = document.getElementById("your_input_id");
input.oninput = function() {
alert(input.value);
};
Unfortunately, it doesn't work in IE <= 8. However, in those browsers you can use the propertychange event on the value property instead:
input.onpropertychange = function() {
if (window.event.propertyName == "value") {
alert(input.value);
}
};
SO regular JavaScript answerer #Andy E has covered this in detail on his blog: https://web.archive.org/web/20140626060232/http://whattheheadsaid.com/2011/10/update-html5-oninput-event-plugin-for-jquery

Use keyup event, an example on jsFiddle
$("textarea").keyup(function(e){
alert($(this).val());
});
It happens after you lift the key. I don't know what you want to achieve, but you can store the state before lifting the key (on keydown or keypress) and restoring later if needed. You also can stop the output in the keyup event using e.preventDefault(), so even after the key is up it will not register the values in the area.

You could listen on keydown event and store the value in a variable. That variable would have the value as it was before the new input, and the new input would be included in the keyup event
UPDATE:
Ok, I misunderstood your requirements, but there isn't an event that would meet your needs. The only thing I can think of to simulate this behaviour is the following:
listen on keydown/keypress
get the value from the event object (get event.which, then convert it to actual value)
use a variable like I mentioned in the original advice and concatenate the new input to it
Here is a fiddle: http://jsfiddle.net/HpXuU/13/
This is obviously not a perfect solution, as it needs some (one might argue unnecessary) work to get done right. I would advise to rethink your needs, but if this behavior is absolutely what you need, I think this is a step in the right direction.

You can use setTimeout:
$('input').keypress(function() {
var that = this;
setTimeout(function() {
// read that.value
}, 0);
});
Live demo: http://jsfiddle.net/HpXuU/8/

Related

Shot event when the value in an input is modified

Consider the following:
<input type="text" id="foo" />
I need that, when the value of the input.#foo is changed, without blur, it shot my event. Here comes the problem: I can't use onkey events because the input is dinamically received by a virtual HTML-composed keyboard.
I can easily do, with the true keyboard:
document.querySelector("#foo").addEventListener('keypress', function() {
// Implementation
});
The W3C recommend using onchange, but onchange only works after the blur event occurs. I need a mix of onkeypress, to be dynamic, on time modify, and onchange, to know when it changes. You can see this: http://jsfiddle.net/zuq733La/
JS Fiddle
use textInput it will check for every character added
document.querySelector("#foo").addEventListener('textInput', function () {
alert('Value changed!');
});
the only way I can think of (without using blur, change, keypress, keyup or keydown events) is using a setInterval(): DEMO
var value=$('#foo').val();
setInterval(function(){
if(value!=$('#foo').val()){
value=$('#foo').val();
//here you need to write what will happen if the value is changed
}
},50);
in the DEMO you can see that even if you copy and paste a text (using only your mouse even without blurring the input) the event fires.

How to display only one key if i hold the key down in the textarea

Is There any possible way to display only one character when a key is pressed DOWN for a longer period of time what I mean is when I press lets say 's' DOWN for a longer period of time I want only 's' displayed and I don't want this to happen 'ssssssssssssssssssssssssssssssssssssssss....' .
And whit out using this method because this brings on the problem that if a user types fast and presses two keys at the same time only the second one will get displayed for example if I press down 'k' and press down whit out letting 'k' go the 'p' only the 'p' will get displayed.
var textarea='';
document.getElementById('textareaID').onkeydown=keydown;
document.getElementById('textareaID').onkeyup=keyup;
function keydown () {
this.value=textarea;
}
function keyup () {
textarea=this.value;
this.value=textarea;
}
And please do not say using counters because it doesn't work for some reason believe me I have tried for the last 3 days.
http://toki-woki.net/lab/long-press/ this is what i am basically trying to do but I cant understand how the part where you hold the key down and only one is displayed out is done and of course if i press a key and while the key is down i press another one both of them get displayed rest is easy.
So i would love and explanation its driving me crazy.
Alright I think I got it.
1: On keydown cancel the input to the textarea.
2: On keyup put in the clicked letter.
document.getElementById('textareaID').onkeydown=keydown;
document.getElementById('textareaID').onkeyup=keyup;
// keydown is run more than once if held down hence "ssssssss"
function keydown (event) {
// cancel input
}
// since the keyup event is only fired once we will do most of the work here
function keyup (event) {
// insert input
}
Here is the code (there are comments so you can see what's going on):
http://jsfiddle.net/NerfAnarchist/gXVuC/
As commenter PA pointed out, I think this is bad practice to alter native behavior of textbox or textareas. See your other options before doing this.
...But IF you have to do it:
You can use the keyDown event to let the event pass on condition that it is followed by a keyUp event. The following code is based on this fiddle.
​document.getElementById('box').addEventListener('keydown', function(event){
// Superglobal window.characterPrinted to detect if the event has already fired.
if(window.characterPrinted != true){
window.characterPrinted = true;
this.value += String.fromCharCode(event.keyCode);
event.preventDefault();
}
})​​​​​​​​;
document.getElementById('box').addEventListener('keyup', function(event){
// Reset superglobal
window.characterPrinted = false;
});
Note that this code uses addEventListener and preventDefault, which is not guaranteed to work in older browsers. You'll need to bind events using different methods. (I'm looking at you, IE7).
Another note: this code adds to the textarea. Therefore, if a delete key pressed, it will try to add a delete, which does nothing. You can do an event.keyCode filtering to see if it's a letter before fiddling with the event itself, much like Michael suggested.

Track/Observe TextBox value changed

Is there is any way to detect text box value changed , whether users changes it explicitly or some java script code modified the text box? I need to detect this change.
To track for user changes you can add a handler for key presses:
$(selector).keypress(function() {
// your code
});
Update: besides watching for key presses,
you can use the change function to watch from changes via JavaScript. It won't work immediatly for user changes (is only called after the input loses focus), but together with the keypress I believe you cover all cases:
$(selector).change(function() {
// the same code
});
setTimeout(function() { $(selector).val("changed"); }, 2000); // Will trigger the change
Edit: sorry, it seemed to work for JavaScript too, but I was mistaken... This question, however, will be able to solve your problem (tested with setTimeout, and it was able to detect the change).
I posted an example in jsFiddle. With this new watch plugin, you no longer need keypress or change: it will work for key typing, copy/pasting, JavaScript, etc.

Detecting input change in jQuery?

When using jquery .change on an input the event will only be fired when the input loses focus
In my case, I need to make a call to the service (check if value is valid) as soon as the input value is changed. How could I accomplish this?
UPDATED for clarification and example
examples: http://jsfiddle.net/pxfunc/5kpeJ/
Method 1. input event
In modern browsers use the input event. This event will fire when the user is typing into a text field, pasting, undoing, basically anytime the value changed from one value to another.
In jQuery do that like this
$('#someInput').bind('input', function() {
$(this).val() // get the current value of the input field.
});
starting with jQuery 1.7, replace bind with on:
$('#someInput').on('input', function() {
$(this).val() // get the current value of the input field.
});
Method 2. keyup event
For older browsers use the keyup event (this will fire once a key on the keyboard has been released, this event can give a sort of false positive because when "w" is released the input value is changed and the keyup event fires, but also when the "shift" key is released the keyup event fires but no change has been made to the input.). Also this method doesn't fire if the user right-clicks and pastes from the context menu:
$('#someInput').keyup(function() {
$(this).val() // get the current value of the input field.
});
Method 3. Timer (setInterval or setTimeout)
To get around the limitations of keyup you can set a timer to periodically check the value of the input to determine a change in value. You can use setInterval or setTimeout to do this timer check. See the marked answer on this SO question: jQuery textbox change event or see the fiddle for a working example using focus and blur events to start and stop the timer for a specific input field
If you've got HTML5:
oninput (fires only when a change actually happens, but does so immediately)
Otherwise you need to check for all these events which might indicate a change to the input element's value:
onchange
onkeyup (not keydown or keypress as the input's value won't have the new keystroke in it yet)
onpaste (when supported)
and maybe:
onmouseup (I'm not sure about this one)
With HTML5 and without using jQuery, you can using the input event:
var input = document.querySelector('input');
input.addEventListener('input', function()
{
console.log('input changed to: ', input.value);
});
This will fire each time the input's text changes.
Supported in IE9+ and other browsers.
Try it live in a jsFiddle here.
As others already suggested, the solution in your case is to sniff multiple events.
Plugins doing this job often listen for the following events:
$input.on('change keydown keypress keyup mousedown click mouseup', handler);
If you think it may fit, you can add focus, blur and other events too.
I suggest not to exceed in the events to listen, as it loads in the browser memory further procedures to execute according to the user's behaviour.
Attention: note that changing the value of an input element with JavaScript (e.g. through the jQuery .val() method) won't fire any of the events above.
(Reference: https://api.jquery.com/change/).
// .blur is triggered when element loses focus
$('#target').blur(function() {
alert($(this).val());
});
// To trigger manually use:
$('#target').blur();
If you want the event to be fired whenever something is changed within the element then you could use the keyup event.
There are jQuery events like keyup and keypress which you can use with input HTML Elements.
You could additionally use the blur() event.
This covers every change to an input using jQuery 1.7 and above:
$(".inputElement").on("input", null, null, callbackFunction);

How to avoid navigate back when the user types backspace on a HTML text input?

Backspace is the browser hotkey for Navigate Back To The Last Page. I know that when an input has the focus this hotkey is disabled. But I have keyup and keydown events binded to this input, and something I wrote is causing this trouble.
Do you know the solution?
when you have handled the event from the input element, cancel that event's bubbling before returning.
I had a similar need i.e. to neutralize the Back action caused by Backspace key and I came across a solution on this site
http://www.webmasterworld.com/javascript/3785986.htm
I hope it will help you.
The problem was caused by the input removal before returning the onKeyDown event.
You can try to hook into window.onbeforeunload event to prevent such accidental navigation.
That you can make:
You can set a listener for InputField and look all keydown events.
In event listener you can make a buffer variable, which have a real InputField value.
So, if you accept a not Backspace code then new value of buffer will be InputField value and you make use your hotKeyFunction, else new value of InputField will be buffer value and you get a normal working of InputField.
if (typeof(window.event)!='undefined')//ie
{document.onkeydown=function()
{var tag_name=event.srcElement.tagName.toUpperCase();
if (tag_name!='INPUT' && tag_name!='TEXTAREA')
{return event.keyCode!=8;
}
};
}
else //firefox, chrome
{window.addEventListener('keydown',function(evt){if (evt.keyCode==8){evt.preventDefault();}}, true);
}
try this on your onKeyDown or onKeyPress even
if (event.keyCode==8)//where 8 ascii code of backspace
{
retunr;
}

Categories