0

I would like to realize a keypress event for typing a string into an input elements by Jquery, I know Jquery can listen the event of keypress, keydown and keyup. But, what I want to do is using the Jquery to realize the action of keypress and put the value of which key I pressed into the input elements. Is that possible by jQuery to realize this task?

Calvin
  • 167
  • 4
  • 14

2 Answers2

1

Is this what you want?

WORKING FIDDLE

$('.input').on('keypress', function(event) {
  event.preventDefault();
  $(this).val(event.keyCode);
});

$( ".input" ).trigger( "keypress" );
Hemal
  • 3,682
  • 1
  • 23
  • 54
0
// Target input element and bind to the "keyPress" event.
$('.input').on('keypress', function(event) {
  // Prevent the default action to stop the key character being entered into the field
  event.preventDefault();
  // Add the event's keyCode into the field
  $(this).val(event.keyCode);
})

http://codepen.io/anon/pen/XXNOQd?editors=101

mark_c
  • 1,202
  • 1
  • 8
  • 10
  • Why the input element still empty as I have tested your code up there, I was thinking, the way we put a value into the input element is: $('#input').val(); But, from your code, I did not find this code, can you help me to modify it? – Calvin Dec 31 '15 at 01:22
  • I've updated the code above now you've clarified the requirements in the question comments. – mark_c Dec 31 '15 at 02:00
  • Thx, but I think you misunderstood my point. I would like to use Jquery to trigger a keypress event, but pressing any keyboard. Meanwhile, also input values into input element. Is that possible to realize? – Calvin Dec 31 '15 at 02:48