如果表单没有有效值,则显示alert()对话框
我有一个简单的表单,它接受来自文本框和文本区域的标题和内容变量。该表单会将其数据发送到名为 add-post.php
的文件。但是,我正在寻找一种方法来提醒用户,如果用户单击提交按钮,文本框或文本区域包含无效数据(为空)。
我认为 alert()
弹出框将是最好的主意,因为它不会重定向到任何其他页面,并且用户永远不会丢失数据(想象一下他们输入了大量文本但忘记了将数据发送到 add-post.php 并在那里执行检查将导致用户丢失数据)。
但是,我不确定如何实际实现 alert()
弹出窗口。我该如何做到这一点,以便在他们单击提交按钮之后但在数据发送到下一个文件之前完成检查。任何建议表示赞赏。
I have a simple form which accepts a Title and a Contents variable from a textbox and a textarea. The form will send its data to a file called add-post.php
. However, I am looking for a way to alert the user that either the textbox or the textarea has invalid data (is empty) in case they click the submission button.
I was thinking that an alert()
popup box would be the best idea because it doesn't redirect to any other page and the user never loses their data (imagine they entered a whole lot of text but forgot a title. Sending the data to add-post.php
and performing the check there will result in loss of data for the user).
However, I'm not sure how to actually implement the alert()
popup. How would I make it so that the check is done AFTER they have clicked the submit button but BEFORE the data is sent off to the next file. Any advice is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您的表单上添加类似这样的内容
然后在 javascript 中
也正如其他人所说的 jQuery 使这变得更容易一些。我强烈推荐 jQuery 验证插件
有些人确实觉得警报框“烦人”,所以它可能最好在 DOM 中附加一条消息,让用户知道需要修复什么。如果存在大量错误,这非常有用,因为错误会更加持久,从而允许用户看到需要修复的所有内容。同样,jQuery Validate 插件内置了此功能。
On your form add something like this
Then in javascript
Also as others have said jQuery makes this a little bit easier. I highly recommend the jQuery Validate Plugin
Some people do find the alert box "annoying", so it may be better to append a message into the DOM to let the user know what needs to be fixed. This is useful if there are numerous errors as the errors will be more persistent allowing the user to see all the things they need to be fixed. Again, the jQuery Validate plugin has this functionality built in.
将
onsubmit
事件附加到表单,并在检查失败时return false;
停止提交。Attach an
onsubmit
event to the form, andreturn false;
to stop the submission if checks fail.使用 Javascript 进行表单验证。 或者使用 jQuery 更容易。
基本上,在单击提交按钮时验证表单(使用 onsubmit 处理程序),然后根据需要使用alert() 框。顺便说一句,人们通常讨厌警报框。
Form validation with Javascript. Or easier with jQuery.
Basically, validate the form when the submit button is clicked (with an onsubmit handler), and then use an alert() box if needed. By the way, people usually hate alert boxes.
当涉及到客户端验证时,您有多种选择。这只是其中之一。
有关更深入的示例,请查看此链接
You have a number of options when it comes to client side validation. This is just one.
For a more indepth example check out this link