Preventing “Enter” from submitting form, but allow it on textarea fields (jQuery) [duplicate]

折月煮酒 提交于 2019-12-01 15:30:11

i would prefer the keyup event ... use the event.target property

$(window).keydown(function(event){
    if((event.which== 13) && ($(event.target)[0]!=$("textarea")[0])) {
      event.preventDefault();
      return false;
    }
  });

demo

You may try this

$(document).ready(function(){
    $(window).keydown(function(event){
        if(event.keyCode == 13 && event.target.nodeName!='TEXTAREA')
        {
          event.preventDefault();
          return false;
        }
    });
});

A fiddle is here.

@3nigma's solution would work just fine but here another way of achieving this behavior:

$(function(){
    $('#myform').find('input,select').keydown(function(event){
        if ( event.keyCode == 13 ){
            event.preventDefault();
        }
    });
});
$('#form_editar').keypress(function(e) {
    var allowEnter = {"textarea": true, "div": true};
    var nodeName = e.target.nodeName.toLowerCase();

    if (e.keyCode == 13 && allowEnter[nodeName] !== true) {
        e.preventDefault();
    }
});

I edit from @The Alpha a bit, i use div for wysiwyg editors :)...

This seems like a good opportunity to use the event object and a scalpel-like approach on this mosquito instead of a cannon-like approach.

In other words, something like this:

...
// Only watch for a bad type of submission when a submission is requested.
$('form .contact-form').submit(function(e){
    // If a submit is requested, and it's done via keyboard enter, stop it.
    if ((e.keyCode || e.which) == 13) ? ;){ // Try to use normalized enter key code
        e.preventDefault(); // Prevent the submit.
    }
    // All other mouse actions just go through.
});

The advantage here should be relatively obvious, if you hit enter anywhere that doesn't submit a form, this code doesn't know, doesn't care, doesn't cause problems.

I have found this works best. Especially if you want to use enter key behaviors in other elements just not to send the form back. I am just expanding on 3nigma's answer.

 $("form").keypress(function (event) {
            if (event.keyCode == 13 && ($(event.target)[0]!=$("textarea")[0])) {
                return false;
            }
        });

Why not just block the form's submit event from triggering instead?

$('form').submit(function(event){
  event.preventDefault();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!