【JS】 途中入力離脱防止 ~ beforeunloadイベント ~

■ 途中入力離脱を防止するには

 * 「beforeunload」イベントを使う

■ サンプル

<!DOCTYPE html>
<html lang="ja">
<head>
  <title>Hello World</title>
</head>
<body>
  <div>
    <a href="index.html">link</a>
  </div>
  <form action="index.html" method="post">
    <div>
      <input type="submit" id="button" value="ClickMe">
    </div>
  </form>
  <script type="text/javascript">
  window.onload = function() {
    // 本来は初期化処理を入れる
  }
  window.addEventListener('beforeunload', function(event) {
    // 本来は判定処理を入れる
    event.returnValue = "移動しますか?";
  });
  </script> 
</body>
</html>


関連記事

Bootstrap 4 ~ Form 編 ~

https://blogs.yahoo.co.jp/dk521123/36103698.html