On keypress does not fire on the first key press - javascript

I have this method:
$(".txtB").on("keypress", function(event) {
console.log($(this).val());
if (...)
event.preventDefault();
});
But it works only after the second key pressed not for the first one. After that is triggered on every key press.
Anyone have an idea what could be?
Thanks.
Later edit:
It might be related to the way i use the function?
in HTML: onkeyup = "caseValuePercentageTwoDecimalRestriction()"
in JS:
function caseValuePercentageTwoDecimalRestriction() {
$(".caseValuePrecentageRestriction").on("keypress", function (event) {
...
??

The error is calling caseValuePercentageTwoDecimalRestriction on keyup event which is fired after keypress event.
keyup is called when you release the key while keypress is called when you press the key.
You should bind you keypress event handler on a document.ready event like this:
$(document).ready(function() {
$(".caseValuePrecentageRestriction").on("keypress", function (event) {
// do whatever you need
});
});

$(".txtB").keyup(function (event) {
console.log($(this).val());
});
To answer your question, Keypress event happens before the input change. But Keyup happens after the change. That's the only difference.

For input fields there is one more property input propertychange which works on change of text by keyboard as well as of you copy from mouse. Try using it
$(".txtB").on("input propertychange", function(event) {
console.log($(this).val());
if (...)
event.preventDefault();
});

use keyup instead of key press - Try:
$(".txtB").keyup(function (event) {
console.log($(this).val());
});

Then maybe .keydown would work for you?

Here we go:
Your code have to be like this:
$("input").keypress(function(){
$("span").text(i += 1);
alert("Test key pres");
});
<input type="text">
<p>Keypresses: <span>0</span></p>
Hope it helps;)

This will work for you but this is not perfect solution, it is just a work around:
$(document).ready(function(){
$(".txtB").on("keypress", function (event) {
console.log($(this).val() + event.key);
});
});
Here is a jsbin
As other users has shared Keypress event triggers before the value of textbox changed. You should use other events if you want updated value of textbox.

keypress events are fired before the new character is added to the input.
So the first keypress event is fired before the first character is added, while the input is still empty.
If you check this JSFIDDLE you will see an alert box even before you see value in input.
For example if you type a initially you will see an empty alert box, then type a different character, at that point you will see it is alerting a
You need to use either keyup or keydown. You can aslo use event.preventDefault() with keyup & keydown

try to use change instead of keypress or keyup because it will call first :
$(".txtB").change(function(event){
console.log($(this).val());
});

Related

keypress handler canceling the event

I have the following code
jQuery('#parent').on('keypress', '.textbox', function(e) {
var btn = jQuery(this).closest('tr').find('.btn');
if (btn.length) {
btn.triggerHandler('click');
}
});
This code is a delegated keypress handler which is listening to the event of textboxes having class value ".textbox".
The handler finds the button with class ".btn" & calls its click handler which has an ajax call in it.
Problem is this seems to prevent the event from completing i.e if the value in box is "2" & I type in a "3",the handler executes but the value in the box remains to be "2" instead of a "23".
It works normal when I comment out the btn triggerHandler statement.
Ideas why this is happening?
Use keyup instead of keypress. As in your script you have triggered another event.
jQuery('#parent').on('keyup', '.textbox', function(e) {
var btn = jQuery(this).closest('tr').find('.btn');
if (btn.length) {
btn.triggerHandler('click');
}
});
keypress gets interrupted by triggerHandler and hence doesn't allow the default action of key press to occur. While keyup will perform default action first, then listen to handler.
I think you need to keyup function.
$(document).ready(function(){
$("input").keyup(function(){
var rs= $(this).val();
alert(rs);
$("input").css("background-color", "pink");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Enter your value: <input type="text">
Try to use 'onchange' insted of 'keypress' or 'keyup'
$(document).ready(function(){
$("input").onchange(function(){
var rs= $(this).val();
alert(rs);
$("input").css("background-color", "pink");
});
});

JQuery focus without entering key event shortcut

Using keymaster library for defining and dispatching keyboard shortcuts, I defined shortcut key / to focus input element.
key('/', function() {
$(".topbar input").focus();
});
The issue is that when the / key is pressed, the input is focused with / entered value. I want to get rid of that.
Try this.
key('/', function(event) {
$(".topbar input").focus();
event.preventDefault();
});
It gets focused because you tell it to do so.
Remove this line:
$(".topbar input").focus();
Or give it a function so that you can do stuff when it gets focused
$(".topbar input").focus(function(){
});

jQuery .on() running before value given

Why does .on() not get the value of the form input field (#forgot) before the keypress has happened.
$(document).ready(function() {
$(document).on('keypress', '#pass', function() {
var value = $.trim($('#pass').val());
alert(value);
if (!value.length) {
alert("Show");
$('#forgot').show();
} else {
alert("Hide");
$('#forgot').hide();
}
});
});
When I type in the first character the alert shows no input. The second character leads to the value being only the first character. The .on() function seems to run before the key press is registered? How can I fix this or is there an alternative function?
keypress event triggered when you press a key. It will not wait for the value to come. Try with keyup. keyup gets triggered when you a key is released after pressing, till that time the value is proccessed. -
$(document).on('keyup', '#pass', function() {
keypress
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.
keyup
The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.
Simply change keypress to keyup:
$(document).ready(function() {
$(document).on('keyup', '#pass', function() {
var value = $.trim($('#pass').val());
console.log(value);
if (!value.length) {
console.log("Show");
$('#forgot').show();
} else {
console.log("Hide");
$('#forgot').hide();
}
});
});
You need the keyup event instead of the keypress.
So replace:
$(document).on('keypress', '#pass', function() {
With
$(document).on('keyup', '#pass', function() {
keypress event is triggered when the key is pressed before the key is up). So it won't get the complete value.
Use keyup
JSFIDDLE DEMO
HTML
<input id="pass">
JQUERY
$(document).ready(function() {
$(document).on('keyup', '#pass', function() {
var value = $.trim($('#pass').val());
alert(value);
if (!value.length) {
alert("Show");
$('#forgot').show();
} else {
alert("Hide");
$('#forgot').hide();
}
});
});

keydown listener for body

So I want to call a function when the space bar is pressed on the page. The only problem is thought that the function can NOT be called if it's focused in an input bar. Any ideas on how to do that?
This code works, but still fires the function when focused in an input bar
$(document).keydown(function(e){
if (e.keyCode==32) {
stopplay();
}
});
update to this:
if (e.keyCode==32 && !$(e.target).is(':input')) {
stopplay();
}
:input is handy if you have other input elems like select, textarea etc it selects all the input elements.
Demo
Use event.stopPropagation() method, to prevent keydown bubbling.
$(':input').keydown(function(e){
e.stopPropagation();
});
Update:
If you have to apply the above to other input elements, use $(':input') selector.
Well you can look to see where the event originated:
$(document).keydown(function(e){
if(!$(e.target).is("input")) {
// it's NOT from an input!
}
});
Use this code
$(document).keydown(function(e){
if (e.keyCode==32 && !$(e.target).is("input")) {
stopplay();
}
});

fire .change with keyup and keydown

I have the following which works as long as I use the mouse to select an option from the selectbox, or use keyboard arrow keys to select the option, but when using the keyboard, the change event does not fire until I press enter on the keyboard.
How would I detect a change using the keyboard arrow keys without having to press enter?
$('#select_box').change(function() {
some_function($(this).val());
});
You'll probably want to avoid calling your function multiple times unnecessarily, which will happen if you are not careful with multiple events. You can avoid this by checking if the value of the field has actually changed before calling it. One way of doing this, shown below, is to store a property on the field with the previous value and then using that to check if the field's value has changed before calling your function:
var previousValuePropertyKey = 'previousValue';
$('#select_box').bind('keyup change', function(event) {
var previousValue = $(this).prop(previousValuePropertyKey);
var currentValue = $(this).val();
$(this).prop(previousValuePropertyKey, currentValue );
if(previousValue != currentValue ){
alert(currentValue);//TODO remove alert
//Yourfunction(..);
}
});
Here's a fiddle for an example.
TRY
$('#select_box').bind('keyup change',function() {
some_function($(this).val());
});
Reference
$('#select_box').change(function() {
alert($(this).val());
});
$('#select_box').keyup(function() {
alert($(this).val());
});

Categories