Rails 3 表单助手可以防止用户离开并丢失更改吗?
如果用户在当前页面的表单中输入了某些内容,是否有 Rails 帮助程序或 Rails 方法可以阻止用户离开当前页面?
我试图防止人们在表单中有未保存的更改时单击标题链接而丢失数据。
Is there a Rails helper or a Rails way of preventing the user from leaving the current page if they're typed something into the form on the current page?
I'm trying to prevent people from losing data if they click a header link if they have unsaved changes in a form.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在提交表单之前,Rails 并不知道表单的状态,但您可以添加一些 JavaScript 来帮助解决这种情况。
编辑:好的,这样只处理标题链接点击(就像您在问题中指定的那样),这是一个使用 onbeforeunload 的解决方案。完整的页面源代码,因为我对其进行了测试,以确保我为您提供了一些可以构建的东西:
当然,这不是特定于 Rails 的帮助程序,但您可以编写自己的帮助程序来吐出带有类似以下内容的脚本标记融入你的观点。您可能还希望进行特定于表单的检查,而不仅仅是检查每个输入是否为空。我制作的每一种形式都是美丽而独特的雪花。
Rails doesn't know about the state of a form until it is submitted, but you can add a pinch of javascript to help in that case.
edit: Okay, so that only handles header link clicking (like you specified in your question), here's a solution that uses onbeforeunload. Full page source because I tested it out to make sure I'm giving you something to build on:
Of course this isn't a Rails-specific helper, but you could write your own helper to spit out a script tag with something like this in it into your views. You'll probably also want to put form-specific checks in rather than just checking every input for emptyness. Every form I've ever made was a beautiful and unique snowflake in some form or another.