按下回车键时写入文本区域?
我有一个用于处理输出的文本区域和一个用于处理用户输入的文本字段。
焦点将完全集中在输入字段上。 我无法使用户输入字段在提交表单时添加文本(按下输入键)。仅当有一个按钮并且被单击时它才会起作用。我该如何解决这个问题?
下面是我尝试输入回车键提交的代码。
<html>
<head>
<script type="text/javascript">
function addtxt(input) {
var obj=document.getElementById(input)
var txt=document.createTextNode("blah blah")
obj.appendChild(txt)
}
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onSubmit="addtxt('textarea1');">
</body>
</html>
I have a textarea, which will handle output, and a textfield which will handle user input.
Focus will be entirely on the input field.
I can't make it so that the user input field will add text when the form is submitted (enter key is pressed). It will only work if there is a button and this is clicked. How do I solve this issue?
Below is the code i'm trying for the enter key submit.
<html>
<head>
<script type="text/javascript">
function addtxt(input) {
var obj=document.getElementById(input)
var txt=document.createTextNode("blah blah")
obj.appendChild(txt)
}
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onSubmit="addtxt('textarea1');">
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这样就可以完成工作了。另外,您应该处理文本区域的
value
属性,而不是向其附加文本节点:如果用户完全更改文本区域的值,则随后更改其子节点将不会产生任何效果。如果您希望文本区域为只读,请添加readonly
属性:。
This will do the job. Also, you should deal with the
value
property of the textarea rather than appending text nodes to it: if the user changes the textarea's value at all, changing its child nodes afterwards will have no effect. If you want the textarea to be read-only, add areadonly
attribute:<textarea id="textarea1" readonly></textarea>
.尝试使用按键事件而不是提交。检测何时按下回车键,复制数据,并取消事件(以防止表单提交)。如果您允许提交表单,它只会将现有页面替换为表单发布的结果。
修改当前代码:
请注意,可能有更好的方法来实现您的最终目标,但由于您没有说明那是什么,这确实是我能做的最好的事情。另外,我肯定会考虑使用像 jQuery/Dojo/Prototype 这样的框架,并以不显眼的方式添加处理程序。
Instead of submit, try using the keypress event. Detect when the enter key is pressed, copy the data, and cancel the event (to prevent form submission). If you allow the form to submit, it will simply replace the existing page with the result of the form post.
Modifying your current code:
Note that there may be much better ways to achieve your ultimate goal, but since you don't state what that is, this is really the best I can do. Also, I'd would definitely look at using a framework like jQuery/Dojo/Prototype and add the handlers unobtrusively.
使用表单元素
Use the form element
您可以使用 JQuery
You can use JQuery