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.
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.
$('#header > a').click(function(){
$('input').each(function(i){
if ( $(this).attr(value) != '' ) {
if ( confirm('are you sure you want to leave this form unfinished?') != 'true' ) {
alert('quitter!);
}
}
});
});
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:
<html>
<head>
<title>Foo</title>
<script>
window.onbeforeunload = function(){
var inputs = document.getElementsByTagName('input');
var unfinished = 'false';
for (var i=0; i<inputs.length; ++i) {
if ( inputs[i].value != '' ) {
unfinished = 'true';
}
}
if ( unfinished == 'true' ) {
return 'Are you sure you want to leave?';
}
}
</script>
</head>
<body>
<form>
<input name='foo'/>
<input type='submit'/>
</form>
<a href='/'>Leave</a>
</body>
</html>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With