2

Is it possible in Javascript/JQuery ?

I have a button on my website and I need to simulate human press key "Enter" when someone clicks the button.

Example: I clicked button and then it automatically pressed Enter key.

riko10
  • 41
  • 1
  • 1
  • 4

1 Answers1

0

I modified this code from the code in this answer,

var onclick = function(){
    var e = $.Event('keypress');
    e.which = 13; // Character 'A'
    $(this).trigger(e);
};

$('button').click(onclick);

You want to define a keypress event, define it as the Enter (13) keypress, and trigger it onclick.

Edit for new question: The keypress, keydown, and keyup events don't actually input anything, they're solely for triggering event bindings. You must also add the input if you want that as well. This line translates the keycode back to a string and appends it to the current value.

$("#test").val($("#test").val()+String.fromCharCode(e.which));

Updated JsFiddle

I also included two commented out lines of code that show two ways to submit the form programmatically.

$('#submit').click();

and

$('#myForm').submit();
Community
  • 1
  • 1
James G.
  • 2,852
  • 3
  • 28
  • 52
  • It doesn't work. See: http://jsfiddle.net/3xTM2/462/ There's no console log after click – riko10 Sep 20 '14 at 09:28
  • @riko10 You missed a hashtag for the id selector. I changed $('test') to $('#test') > http://jsfiddle.net/3xTM2/464/ – James G. Sep 20 '14 at 09:32
  • After click on submit I want to simulate click 'a' key (65) at input form. See: http://jsfiddle.net/3xTM2/466/ Why 'a' doesn't display after clicking submit? – riko10 Sep 20 '14 at 09:45