Calvin
Calvin

Reputation: 177

How to call a keypress event by Jquery without pressing any keys

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?

Upvotes: 0

Views: 1388

Answers (2)

Hemal
Hemal

Reputation: 3760

Is this what you want?

WORKING FIDDLE

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

$( ".input" ).trigger( "keypress" );

Upvotes: 1

mark_c
mark_c

Reputation: 1212

// 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

Upvotes: 0

Related Questions