HTML 文本输入事件
我有一个表单,想要根据表单的输入文本字段是否为空或是否已输入文本来禁用/启用其提交按钮。
我认为这意味着为输入文本字段的 keydown
或 keypress
事件提供一个事件处理程序:当它被触发时,该事件处理程序应该测试输入文本字段是否包含文本,并相应地启用或禁用提交按钮。
change
事件看起来应该比 keydown
或 keypress
事件更有用,只不过它在控件输入之前不会被触发。问题失去了焦点,这有什么好处:由于用户只想输入一些内容,然后单击提交按钮,我想要一个由输入的文本触发的事件处理程序,而不仅仅是在控件失去焦点时触发。
我的问题是:
keydown
和/或keypress
事件是在相应文本插入输入文本字段之前还是之后触发的?keydown
和/或keypress
事件是否可以取消(您可以取消它们以防止输入相应的文本)吗?
编辑:仅供参考,jQuery 验证插件 - 测试按键上的表单有效性。
I have a form, and want to disable/enable its submit button depending on whether the form's input text fields are empty or have had text entered into them.
I think this means having an event handler for the input text fields' keydown
or keypress
events: when it's fired, this event handler should test whether the input text fields contain text, and enable or disable the submit button accordingly.
The change
event looks like it ought to be more useful than the keydown
or keypress
events, except that it isn't fired until the control in question loses the focus, and what good is that: since the user wants to just type something and then click on the submit button, I want an event handler that's fired by text being entered and not only when the control loses focus.
My questions are:
- Are
keydown
and/orkeypress
events fired before or after the corresponding text has been inserted into the input text field? - Are
keydown
and/orkeypress
events cancellable (can you cancel them to prevent the corresponding text from being entered)?
Edit: FYI, the jQuery validation plug-in re-tests form validity on key up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
回答你的问题...
在输入文本之前被拦截
使用 javascript
按键或按键功能
事件。这将阻止文本
从被输入。
使用 jQuery 的示例:
如果您想测试表单提交时的某些输入值,您可以使用 jQuery 提交()。
返回 false 将使提交表单的点击无效。
编辑:
如果正如您在评论中所说,您想要禁用表单提交,直到满足输入字段的要求,
您想要使用“keyup" 事件处理程序以允许首先发送文本。请参阅我的示例:在 jsbin 上
In answer to your questions...
be intercepted before text is input
using javascript
function to the keydown or keypress
event. This will prevent the text
from being input.
Example using jQuery:
If you want to test some input for value on form submit you can do that using jQuery submit().
Returning false will invalidate the click to submit the form.
Edit:
If as you say in your comments you want to disable the submission of the form until requirements are met for the input field(s)
You want to use the "keyup" event handler to allow the text to be sent first. see my example: on jsbin