Passthrough global keyboard events to a textfield

问题: Is there any way to replay a keyboard event to a textfield and also make the receiving input field add that character to its text? Because I can't make it to work. Let's...

问题:

Is there any way to replay a keyboard event to a textfield and also make the receiving input field add that character to its text? Because I can't make it to work.

Let's say I press a on the keyboard and a global handler on body captures it. Now I want to replay it to a given textfield. So if the user presses a on the keyboard it would show up inside the textfield, solely based on the event. The event pops up at the input, but the character is not inputted. Is this possible? I want to avoid manipulating the input text with .val();

Example:

$('body').on('keyup', eKeyUp);
$('#mancineni').on('keyup', eKeyUpINPUT);

function eKeyUp(e)
{
 
  $e = $.Event('keyup');
  $e.which = e.which;
  $e.charCode = e.charCode;
  $e.keyCode = e.keyCode;
  $e.shiftKey = e.shiftKey;
  $e.key = e.key;

  $('#mancineni').trigger($e);
    //$('#mancineni').focus();
}


function eKeyUpINPUT(e)
{
    console.log('g', e)
    e.stopPropagation();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mancineni">


回答1:

It feels like you are making this much more difficult than it actually is. Just set the value of the input to event.key while handling it at the body level. Not sure why the need to avoid doing that, perhaps you could explain.

$('body').on('keyup', eKeyUp);
$('#mancineni').on('keyup', eKeyUpINPUT);

function eKeyUp(e){
  $('#mancineni').val(event.key);
}

function eKeyUpINPUT(e){
    e.stopPropagation();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mancineni">

  • 发表于 2020-06-27 19:17
  • 阅读 ( 101 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除