JQuery catching input value one character late - javascript

I'm catching value of an input field:
$('#input').on("keydown", function(){
var city = $(this).val();
console.log(city);
});
When I type 'n' console returns nothing, I type 'ne' it returns 'n', type 'new' it returns 'ne'.
Why is this happening?

It's not catching it late, it's doing what it's supposed to, that is show the letters in console while the key is being pressed. A letter would appear in the input box only after the key has been released, which is why you see it on the next key press.
What you need is the .keyup() event:
$('#input').on("keyup", function(){
DEMO

Use keypress event instead of keydown event.

As my comment states, the keydown event occurs when the key is pressed but before the key value is added to the field. It is possible you may wish to prevent the key being added to the field or to implement some shortcuts, and this event is the opportunity to do so.
For a more complete explanation, read the JQuery Keyboard events section

try this code,hope keyup will work
$('#input').on("keyup", function(){
var city = $(this).val();
console.log(city);
});

The keydown event is sent to an element when the user first presses a key on the keyboard.To determine which key was pressed, examine the event object that is passed to the handler function.
While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows.
For catching actual text entry, .keypress() may be a better choice.

try this code,hope it will work for you
$("#input").keyup(function() {
console.log($(this).val());
});

You have to use keyup in order to get what you want
$('#input').on("keyup", function(){
var city = $(this).val();
console.log(city);
});
think this is what you want

Related

How to detect first character of input on keypress()

I'm using jquery's function keypress for my input field
Now, let's say that I want to know when the user types a letter, if this is the first character in the field. I now use something like:
element.keypress(function(e){
//...
if(elementValue.length()==0){
//Do something
}
}
The problem is when the user selects the text that typed and then presses a key (lets say for the character 'A') that replaces it. Then this code returns the length of the old-(soon to be replaced) text.
I know that I could use keyup instead, but I think I need to stay with keypress because I have to do some checks for the pressed physical keys. (this answer really shows the difference between keyup and keypress in this case)
Any suggestions?
User Paul S. put me in the right direction...
That's what I have now and it works:
element.keypress(function(e){
//...
if(this.selectionStart==0){
//Do something
}
}
This way I detect when a key has been pressed while the caret was just at the beginning of the field.

Detecting Special Key Presses in Javascript

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.

Get text box value when I type the value by every key press

I want to know get text box value when I type the value by every key press.
I have to get the value.
If I type numbers I have to get, so I have checking with that value.
var my_input = document.getElementById('my_input');
my_input.onkeyup = function() {
alert(my_input.value);
}
<input type='text' id='my_input' />
Probably you will have to serve events on input field: onkeypress, onkeyup, onkeydown, onpaste, onchange.
You can get the value of an input element from its value property, e.g.
element.value
To execute some function on every key press, you should bind an event handler for the keyup event to this element.
You should make yourself familiar with event handling in JavaScript and the variations in the different browsers. The site I linked to (quirksmode.org) is a very good resource for that.
One thing to note is that in certain browsers the method by which you get the value of a textarea differs. I'm thinking in IE6, at least, it actually registers the value of a textarea as it's innerHTML (or the other way around).
Worth doing a check in you eventListener for if the value is set, or not, and checking the innerHTML if it's not, just in case!

how to check if the value of a text input is empty right after the keypress event in javascript?

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

Jquery Keypress is not working for my input box

$("#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.

Categories

Resources