11

Possible Duplicate:
jQuery get input value after keypress

I'm trying to get an input text value on jQuery .keypress() function. I've seen various examples with keypress and keydown, but not dedicated on getting the input value. Is it possible?

$(document).ready(function(){
    $("#my_field").keydown (function (e) {
        alert (e);
    });
});

The returned object has a series of properties but I haven't seen something for value input field attribute.

Is there some way to get it?

Community
  • 1
  • 1
vitto
  • 19,094
  • 31
  • 91
  • 130

4 Answers4

13

I'm unclear which you're after here, in case you're after the letter pressed, not the whole value, you can use String.fromCharCode(), for example:

$(document).ready(function(){
  $("#my_field").keydown (function (e) {
     alert (String.fromCharCode(e.which));
  });
});

You can give it a try here

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 2
    When I try to type numbers from the keypad, it's not the same result as if I were to type the numbers not from the keypad.. – gerl Nov 20 '13 at 14:47
6

I'm trying to get a input text value

Use the val():

$("#my_field").keydown (function (e) {
    alert ($(this).val());
});

Assuming that #my_field is the id of input field you want to get the value of.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • @Vittorio Vittori: You are welcome :) – Sarfraz Aug 09 '10 at 12:10
  • 51
    This will not include the character that was just pressed. – andrewrk Feb 08 '12 at 07:06
  • 4
    Inside the keydown function, add this for including the just pressed key setTimeout(function() { console.log($('#search').val()) }, 5) – Marius Mar 15 '12 at 11:34
  • pure javascript. var c = String.fromCharCode(e.which); alert(c) – Shahrokhian Sep 10 '12 at 06:19
  • 4
    As @superjoe30 said, it won't include the character that was just pressed. The real solution is to get the value of the input on `keyup` event: http://stackoverflow.com/questions/8795283/jquery-get-input-value-after-keypress – Alejandro García Iglesias Sep 11 '12 at 19:24
  • 2
    In order to get the best result, and thus getting the LAST character entered, use keyup instead. http://api.jquery.com/keyup/ Keyup is fired AFTER the last character is entered, whereas keydown is entered BEFORE the last character is entered. – dxhans5 Oct 10 '14 at 18:20
2

You could look at event.which:

$(function() {
    $('#my_field').keydown(function(e) {
        alert(e.which);
    });
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
-3

If you want the whole input field value look at this where your alert is:

$(this).val()
Tahbaza
  • 9,486
  • 2
  • 26
  • 39