Javascript 向 textarea 添加新行字符而不是提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14020334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add new line character to textarea instead of submitting form
提问by Khizar
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.
我有一个带有文本区域的表单,按回车键提交我的表单。我怎样才能让它添加一个新行字符而不是表单提交。
回答by Muhammad Talha Akbar
$('textarea').keypress(function(event) {
if (event.which == 13) {
event.stopPropagation();
}
});?
回答by ma?ek
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 Enterinserts a \nin a textarea for me and does notsubmit forms by default.
对于它的价值,我在 OS X 上使用 Chrome 并在文本区域中为我Enter插入一个\n,并且默认情况下不提交表单。
回答by Abhinav Chauhan
$(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.
这可以通过我上面给出的 jquery 代码来完成。必须注意,在HTML输入字段代码之前编写上述脚本时需要使用ready函数,而在输入字段代码之后编写时则不需要。如果不起作用,请尝试使用\t代替\它将起作用。
回答by Karthik Chintala
you can try this code:
你可以试试这个代码:
$(document).ready(function() {
$("textarea").keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
回答by Rusty Fernandez
$(document).ready(function() {
$('textarea').keydown(function(event){
if (event.keyCode == 13) {
event.preventDefault();
var s = $(this).val();
$(this).val(s+"\n");
}
});
});
回答by David Rice
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 的当前值,而只是附加一个新行字符。以下内容阻止事件冒泡到表单,并仍然允许“输入”上的典型 textarea 行为。
$('textarea').keydown(function(event) {
if (event.keyCode === 13) {
event.stopPropagation();
}
});
回答by Alina Malchanava
This worked for me
这对我有用
$(document).keypress(function(e) {
if(e.which == 13) {
if(document.activeElement.tagName != "TEXTAREA") {
e.preventDefault();
};
}
})

