0

I have a basic input field. When the page finishes loading I'd like to automatically focus on the input field, set a value, and finally trigger an 'enter' keypress without having a user trigger these events.

In the code below, the first two steps work fine, but the enter key is never triggered (I have an alert when it is triggered). Can anyone provide insight into how this can be accomplished?

$(document).ready(function () {
    $("#myInput").focus();
    var e = jQuery.Event("keydown");
    e.which = 13;
    $("#myInput").val("test");
    $("#myInput").trigger(e);
});
Kode_12
  • 4,506
  • 11
  • 47
  • 97
  • [jQuery - keydown / keypress /keyup ENTERKEY detection?](http://stackoverflow.com/questions/3462995/jquery-keydown-keypress-keyup-enterkey-detection) – Tân Dec 23 '16 at 03:43
  • That solution refers to a user triggered event, I would like to automate this event when the page loads – Kode_12 Dec 23 '16 at 04:15
  • What should be your end result? Do you want a form to be submitted, or what, because your code works fine. – 31piy Dec 23 '16 at 04:44
  • I want a function to be fired after the input field is entered. The function checks the format of the input – Kode_12 Dec 23 '16 at 04:46

2 Answers2

0

May be adding keyCode would fix your issue.

 $(document).ready(function() {
        $("#myInput").focus();
        var e = jQuery.Event("keypress");
        e.which = 13; 
        e.keyCode = 13; 
        $("#myInput").val("test");
        $("#myInput").trigger(e);
 }); 
ScanQR
  • 3,740
  • 1
  • 13
  • 30
  • Thanks for the reply, this answer is not quite what I'm looking for. I want to have an enter keypress fire automatically, without having the user trigger the keypress – Kode_12 Dec 23 '16 at 03:54
  • @Kode_12 i have updated my answer. Please try to add keyCode. – ScanQR Dec 23 '16 at 04:03
  • I've tried that as well. Still doesn't trigger the enter key :( Is it even possible to automate an event without introducing selenium? – Kode_12 Dec 23 '16 at 04:12
0

I tried the fllowing and this works. Maybe you should check the keydown event handler and where you call it. If you move the keydown event handler at the bottom after trigger function it won't work.

$(document).ready(function() {

            var e = jQuery.Event('keydown', {
                which: 50
            });
            
            $('input').keydown(function() {
                alert("triggered!");
            });

            $('input').trigger(e);

        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="button" value="button">
ibubi
  • 2,469
  • 3
  • 29
  • 50