简体   繁体   English

将新行字符添加到textarea而不是提交表单

[英]Add new line character to textarea instead of submitting form

I have a form with a text area and hitting the enter key submits my form. 我有一个带有文本区域的表单,然后点击回车键提交我的表单。 How can I make it to add a new line character instead of a form submit. 如何使其添加新行字符而不是表单提交。

$('textarea').keypress(function(event) {
   if (event.which == 13) {
      event.stopPropagation();
   }
});​

JSFiddle Demo JSFiddle演示

This should help 这应该有所帮助

$('#myProblematicForm textarea').keypress(function(event) {
  if (event.which == 13) {
    event.preventDefault();
    this.value = this.value + "\n";
  }
});

For what it's worth, I'm using Chrome on OS X and Enter inserts a \\n in a textarea for me and does not submit forms by default. 对于它的价值,我在OS X上使用Chrome并且在我的textarea中输入 \\n ,并且默认情况下提交表单。

$(document).ready(function(){
$("#text").keypress(function(event) {   
   if (event.which == 13) { 
      var s = $(this).val();
      $(this).val(s+"\n");  //\t for tab
   }
});      
});

This can be done by jquery code that I have given above. 这可以通过我上面给出的jquery代码来完成。 Must notice that the use of ready function is necessary when you write above script before the codes of the HTML input field, and not necessary when you write it after the input field codes.If it not working try to use \\t in place of \\n it will work. 必须注意,当您在HTML输入字段的代码之前编写上述脚本时,必须使用就绪函数,而在输入字段代码之后编写它时则不必。如果它不起作用,请尝试使用\\ t代替\\它会起作用。

you can try this code: 你可以试试这段代码:

$(document).ready(function() {
  $("textarea").keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});
$(document).ready(function() {
  $('textarea').keydown(function(event){
    if (event.keyCode == 13) {
      event.preventDefault();
      var s = $(this).val();
      $(this).val(s+"\n");
    }
  });
});

Previous answers don't handle splitting the current value of the textarea and simply appends a new line character. 以前的答案不处理拆分textarea的当前值,只是添加一个新的行字符。 The following stops the event from bubbling up to the form and still allows typical textarea behavior on 'enter'. 以下操作可以阻止事件冒泡到表单,并且仍然允许在'enter'上执行典型的textarea行为。

$('textarea').keydown(function(event) {
  if (event.keyCode === 13) {
    event.stopPropagation();
  }
});

This worked for me 这对我有用

$(document).keypress(function(e) {
if(e.which == 13) {
    if(document.activeElement.tagName != "TEXTAREA") {
        e.preventDefault();
    };
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM