0

I am trying to disable submitting a form when the user presses enter on input fields, but I can't seem to get anything to work. The latest script I've tried was adding this to the head:

<script type="text/javascript">
    $(document).ready(function() {
        $(window).keydown(function(event){
            if(event.target.tagName != 'INPUT') {
                if(event.keyCode == 13) {
                    event.preventDefault();
                    return false;
                }
            }
        });
    });
</script>

I am not receiving any errors in the console so I can't tell if something is conflicting.

1
  • 3
    You want $('form').on('submit', function(e) { e.preventDefault(); }) Commented Feb 2, 2016 at 19:06

2 Answers 2

3

Right now you're capturing the event in the window, so preventDefault() isn't going to do what you want it to. you need to capture it from the form so you can prevent its default submit action

Try:

$('form').on('keyup keypress', function(e) {
  var keyCode = e.keyCode;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});
Sign up to request clarification or add additional context in comments.

7 Comments

You should replace the delegation of 'keyup keypress' event with 'submit', else that piece of code is going to execute on everytime user interact with the form.
I disagree. I think it makes more sense to check on every keypress. All this is checking is if the key code is 13, so it's not like running it each time is a lot of overhead
the condition keyCode === 13 is checked inside the function. That means , irrespect what key is pressed, the function would always be invoked.
right, I'm not saying it's not going to run. I'm just saying all it's gonna do is check the key code and move on. it's a single comparison calculation so it's almost negligible
Discarding all 'submit' events would prevent the form from being submitted by any means. If this is acceptable (i.e. if the OP intends to collect form data and submit it via AJAX), then it's both cleaner and more performant than listening to key events.
|
0

You can use event capturing for that.

    window.addEventListener('keydown',function(event) {
        if(event.target.tagName != 'INPUT') {
            if(event.keyCode == 13) {
                event.preventDefault();
                return false;
            }
        }
    }, true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.