フォームに何か入力された状態でページを移動しようとしたとき確認してくるダイアログを表示する。
sample
$(document).ready(function () {
/*
* フォーム中のINPUT要素等に入力された
* 文字列長から変更の有無を判定する
*/
isChanged = function () {
textLength = 0;
$('input[type="text"]').each(function () {
textLength += $(this).val().length;
});
$('input[type="email"]').each(function () {
textLength += $(this).val().length;
});
$('input[type="number"]').each(function () {
textLength += $(this).val().length;
});
$('input[type="tel"]').each(function () {
textLength += $(this).val().length;
});
$('input[type="checkbox"]:checked').each(function () {
textLength += $(this).val().length;
});
$('textarea').each(function () {
textLength += $(this).val().length;
});
return (textLength > 0);
};
/*
* 他の画面へ移動する直前に入力状況を確認し、
* 入力がある場合警告を表示する
*/
$(window).on('beforeunload', function () {
if (isChanged()) {
return 'このページを離れようとしています。';
}
});
/*
* フォームが送信されるときは、beforeUnloadイベントを消しておかないと
* 「このページを離れようとしています」が表示されてウザい
*/
$('form').on('submit', function () {
$(window).off('beforeunload');
});
});
フォームのデフォルト値などが設定されてるとこの仕組みでは上手く判定してくれないので、デフォルト値を含んでいるときはそれとの比較をしたり色々やらないといけない。