我如何知道表单输入已更改?
我有一个由 <% Ajax.BeginForm() {} %>
生成的表单,其中包含大量输入和 texareas。
当输入值发生变化时,我需要了解它并将输入和表单标记为“脏”。如果用户尝试在不保存的情况下离开页面,我会要求他或她确认放弃更改。
对于如何做到这一点有什么建议吗?
I have a form generated by <% Ajax.BeginForm() {} %>
which contains a lot of inputs and texareas.
When an input value change, I need to know about it and mark the input and the form as "dirty". If the user tries to leave the page without saving, I will ask him or her to confirm abandoning changes.
Any suggestion to how this should be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
复活这个老问题是因为我想到了一个更简单/更好的方法。您可以序列化初始表单数据,存储它,然后稍后再次序列化并检查它是否已更改,而不是侦听各种输入上的事件,如下所示:
这里的另一个优点是,如果用户进行更改,然后恢复它,此检查将报告表单为干净的。
Resurrecting this old question because I thought of a simpler/better way. Instead of listening to events on the various inputs, you can serialize the initial form data, store it, and then serialize it again later and check if it's changed, like this:
One additional advantage here is that if the user makes a change and then reverts it, this check will report the form as clean.
html 控件包含一个保存原始值的属性。您可以将该值与当前值进行比较,看看是否有任何变化。
The html controls include a property that holds the original value. You could compare this value with the current value to see if there have been any changes.
来自 jQuery 文档:
您可以这样做来仅检查输入并在用户尝试退出而不保存更改时通知用户。
jQuery API .change()
From jQuery Docs:
And you could do like this to check only the inputs and have user notified, if they try to exit without saving changes.
jQuery API .change()
我会用 jQuery 来做这件事。它会是这样的(只是一个草稿,您可能需要添加/更改一些代码):
然后,在发布之前,检查是否存在脏输入。您甚至可以使用 dirty css 类添加一些颜色。
编辑:拼写错误将“更改”修复为“更改”
I would do this with jQuery. It would be something like this (just a draft, you may need to add/change some code):
Then, before POSTing, check if there is a dirty input. You can even add some color by using the dirty css class.
EDIT: typo fixed 'changed' to 'change'
您可以使用 jquery 插件 dirrty 来识别表单是否脏。
https://github.com/rubentd/dirrty
在 on("dirty") 事件中设置一些全局的变量为 true 来标识表单已更改。
处理
window.onbeforeunload
或$(window).unload()
事件并根据该变量值获取用户确认。该插件的优点是您可以使用 'on("clean") 事件再次跟踪表单是否更改为原始值
You could use jquery plugin dirrty for identifying form dirty.
https://github.com/rubentd/dirrty
In on("dirty") event set some global variable to true to identify form has changed.
Handle
window.onbeforeunload
or$(window).unload()
event and get confirmation from user based on that variable value.The advantage of this plugin is you can track back if form is changed to original values again using 'on("clean") event