Add new line character to textarea instead of submitting form

≯℡__Kan透↙ 提交于 2019-12-05 13:32:32

问题


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.


回答1:


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

JSFiddle Demo




回答2:


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.




回答3:


$(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. 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.




回答4:


you can try this code:

$(document).ready(function() {
  $("textarea").keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});



回答5:


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



回答6:


Previous answers don't handle splitting the current value of the textarea and simply appends a new line character. The following stops the event from bubbling up to the form and still allows typical textarea behavior on 'enter'.

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



回答7:


This worked for me

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


来源:https://stackoverflow.com/questions/14020334/add-new-line-character-to-textarea-instead-of-submitting-form

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