1

I have jQuery function that detect if some key in keyboard pressed. So far that worked, example if I press "P" then it will focus to textbox.

$(document).keyup(function(e)
{
if (e.keyCode == 51 || e.keyCode == 52 || e.keyCode == 80 || e.keyCode == 65)
{
    $("#code_read_box").focus();
}
});

Now I want when I press "P", "P" will set too to textbox.

<input type="text" id="code_read_box" value=""/>

Any advice ?

DEMO here

4

2 回答 2

2

使用String.fromCharCode

String.fromCharCode(e.keyCode)

演示:http: //jsfiddle.net/hw2g5/

你的代码:

$(document).keyup(function(e) {
  if (e.keyCode == 51 || e.keyCode == 52 || e.keyCode == 80 || e.keyCode == 65) {
    $("#code_read_box").focus();
    $("#code_read_box").val(String.fromCharCode(e.keyCode));
  }
});

如果要附加值,则:

$("#code_read_box").val($("#code_read_box").val() + String.fromCharCode(e.keyCode));
于 2013-07-30T07:54:23.057 回答
0

解决了。

$(document).keyup(function(e) {
    var key = String.fromCharCode(e.keyCode);

    if (key.match(/[34PA]/) && !$('input').is(':focus')) {
        $('input').focus();
        $('input').val($('input').val() + key);
    }
});
于 2013-07-30T07:54:04.537 回答