Javascript 在 jQuery 按键事件上获取输入文本值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3430628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:35:00  来源:igfitidea点击:

Get input text value on jQuery keypress event

javascriptjquery

提问by vitto

Possible Duplicate:
jQuery get input value after keypress

可能的重复:
jQuery 在按键后获取输入值

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

我正在尝试获取功能input textjQuery.keypress()。我已经看到了各种有关 keypress 和 keydown 的示例,但并未专门用于获取输入值。是否可以?

$(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?

有什么办法可以得到吗?

采纳答案by Sarfraz

I'm trying to get a input text value

我正在尝试获取输入文本值

Use the val():

使用val()

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

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

假设这#my_field是您要获取其值的输入字段的 id。

回答by Nick Craver

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:

我不清楚你在这里追求的是哪个,如果你在按下字母而不是整个值,你可以使用String.fromCharCode(),例如:

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

You can give it a try here

你可以在这里试一试

回答by Darin Dimitrov

You could look at event.which:

你可以看看event.which

$(function() {
    $('#my_field').keydown(function(e) {
        alert(e.which);
    });
});

回答by Tahbaza

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

如果您想要整个输入字段值,请查看警报所在的位置:

$(this).val()