按回车键时,文本区域不会停止创建新行

Textarea does not stop making new line when Enter key is pressed

本文关键字:创建 新行 区域 回车 文本      更新时间:2023-09-26

我不明白为什么我的文本区域不会停止创建新行,并且在按下 Enter 时不会调用函数,因为 jquery 就是这样做的。通过输入,它可以正常工作。是的,我仍然想要那个提交按钮。

JavaScript

function da(){
$('#com').unbind('keypress').bind('keypress', function(e){
   var code = e.keyCode ? e.keyCode : e.which;
   if(code == 13) // Enter key is pressed
   {  e.preventDefault();
      chat();
   }
});
}

.HTML

<form id='com' method='post'>

Mesaj:<br>
<textarea name='mesaj' rows='7' col='60'></textarea><br/><br/>
<input type='submit' value='Trimite mesaj!' onclick='chat()'>
</form>"

要停止换行符(以及回车符),您需要使用 keycode 捕获10以及keypress上的13

请参阅此代码片段:

$("textarea").on("keypress", function(e) {
    if ((e.keyCode == 10 || e.keyCode == 13)) {
        e.preventDefault();
        chat();
    }
});
function chat() {
    alert("hello chat");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name='mesaj' rows='7' col='60'></textarea><br/><br/>
<input type='submit' value='Trimite mesaj!' onclick='chat()' />

你可以这样做,检查我的代码和示例示例供您参考

$(".Post_Description_Text").keydown(function(e){
		if (e.keyCode == 13)
		{
		e.preventDefault();
      	}
	});
.Post_Description_Text{ 
    width:400px;
    height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<textarea name="comment_text" id="comment_text"  class="Post_Description_Text" rows="5"></textarea>
	<button id="check_btn">click here to check</button>

试试这个:

HTML(将id添加到您的文本区域):

<form id='com' method='post'>
    Mesaj:<br>
    <textarea name='mesaj' id="mesaj" rows='7' col='60'></textarea><br/><br/>
    <input type='submit' value='Trimite mesaj!' onclick='chat()'/>
</form>

JS(按回车键时避免换行):

$('#mesaj').keydown(function(e) {
    if(e.which == 13) {
        e.preventDefault();
        chat();
    }
});

JSFIDDLE: http://jsfiddle.net/ghorg12110/p3ufLjoe/