0

If someone presses the Enter key I want to simulate as if he has pressed the space bar. I tried the below but it is not working. Pressing enter does nothing. Please help

$(document).ready(function() {
  var spacepress = $.Event("keypress", {
    keycode: 32,
    which: 32
  });
  $('input').on("keypress", function(e) {
    if (e.which == 13) {
      e.preventDefault();
      $('input').trigger(spacepress);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text'>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
beginner
  • 2,366
  • 4
  • 29
  • 53

1 Answers1

0

The problem is that trigger will fire off any event handlers assigned to a given event but it does not simulate hitting the actual button on the keyboard. You'll have to handle that yourself.

Here's one way of doing it.

$(document).ready(function() {
  var spacepress = $.Event("keypress", {
    keycode: 32,
    which: 32
  });
  $('input').on("keypress", function(e) {
    if (e.which == 13) {
      e.preventDefault();
      $('input').trigger(spacepress);
    } else if (e.which === 32) {
      $(this).val($(this).val() + ' ');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text'>
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • why we need to use elseif – beginner Jan 16 '17 at 19:58
  • @beginner Because that's how I'm handling the space event. Again, you aren't actually simulating hitting the spacebar with trigger. That's impossible. Instead, you're sending out an event that *looks like* the user hit the spacebar. That `else if` section is handling the case where it appears as though the user is hitting the spacebar. – Mike Cluck Jan 16 '17 at 19:59
  • `if (e.which == 13) { e.preventDefault();$(this).val($(this).val() + ' ');` – beginner Jan 16 '17 at 20:02
  • @beginner You could do it that way if you wanted. – Mike Cluck Jan 16 '17 at 20:18