[英]How to submit a form when the Enter Key on a textarea?
I want to submit the content in the textarea as shown below by just hitting the Enter
key on any keyboard on planet earth. 我想通过单击地球上任何键盘上的
Enter
键,在文本区域中提交内容,如下所示。 When the user hits the Shift+Enter
key, the caret has to go to a new line and on hitting Enter
the submitted textarea content should have the new lines created when the Shift+Enter
was pressed. 当用户按下
Shift+Enter
键时,插入符号必须转到新行,并且在Enter
,提交的文本区域内容应具有按下Shift+Enter
时创建的新行。 The content of the textarea should be inserted after the the div with class commentWrap
but the last submitted comment should apear last and vice verser. textarea的内容应在div之后插入带有
commentWrap
类的commentWrap
但最后提交的注释应出现在最后,反之亦然。
I want this solution to work in all browsers. 我希望该解决方案能在所有浏览器中使用。
<div class="commentWrap"></div>
<textarea id="test"></textarea>
<script type="text/javascript">
$(document).ready(function() {
$("#test").keypress(function(e) {
var textVal = $(this).val();
if(e.which == 13 && e.shiftKey) {
//What should I really do here
}
else if (e.which == 13 && ! e.shiftKey) {
e.preventDefault(); //Stops enter from creating a new line
//this.form.submit(); //or ajax submit
if (this.value ==="") {
alert("Hey punk! Put some text before you hit enter.");
}else {
alert(textVal);
$("<div class='comment'>"+ textVal +"</div>").insertAfter('.commentWrap');
}
}
});
});
</script>
//What should I really do here
//我应该在这里真正做什么
Nothing I think, all browsers will insert a new line if shift + enter was pressed so you can just return true; 我认为,如果按下shift + enter,所有浏览器都不会插入新行,因此您可以返回true;
如果您已经具有用于提交表单的提交按钮,则只需触发点击处理程序即可。
$("#submitButton").click();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.