Posted By

nialace on 11/21/10


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Priestd09


Prevent Early Form Submission by Hijacking the Enter Key


 / Published in: JavaScript
 

URL: http://davidwalsh.name/prevent-early-form-submission-hijacking-enter-key

A customer asked me to create a timecard form a few years ago. Everything with the form worked great but users would mistakenly press the enter key before their form was completed. They asked that I make the enter key move the cursor to the next input instead of submitting the form. This is how I'd do that using MooTools JavaScript. The MooTools JavaScript:

  1. var inputs = $$('input.hijack');
  2.  
  3. $each(inputs,function(el,i) {
  4.  
  5. el.addEvent('keypress',function(e) {
  6.  
  7. if(e.key == 'enter') {
  8.  
  9. e.stop();
  10.  
  11. if(inputs[i+1]) { inputs[i+1].focus(); }
  12.  
  13. //last one?
  14.  
  15. if(i == inputs.length-1) { $('submit-button').focus(); }
  16.  
  17. }
  18.  
  19. });
  20. });

Report this snippet  

You need to login to post a comment.