LoginSignup
2
2

More than 5 years have passed since last update.

フォーム画面から移動する際のナビゲーションの確認ダイアログを表示する

Posted at

フォームに何か入力された状態でページを移動しようとしたとき確認してくるダイアログを表示する。

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');
  });
});

フォームのデフォルト値などが設定されてるとこの仕組みでは上手く判定してくれないので、デフォルト値を含んでいるときはそれとの比較をしたり色々やらないといけない。

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2