LoginSignup
0
2

More than 3 years have passed since last update.

ログイン機能

Last updated at Posted at 2021-04-21

ゲームのログイン機能の実装の備忘録です。

今回は、ユーザーが既に会員登録済みという想定で実装していきます。
ソースは以下のようになります。

index.html
<section>
    <h1 class="title">入室許可証</h1>
    <form  action= "room.html" id="log" class="log" name="login">
      <input  type="text">
      <input  type="password">
      <input  class="btn" type="submit" name="date" value="送信">
    </form>
  </section>
  <script>
    document.getElementById('log').onsubmit = function() {
      // event.preventDefault();
      console.log('送信');
      // window.confirm('入室しますか??');
      if (window.confirm('入室しますか??')) {
        console.log('ゲームを開始します');
      } else {
        console.log('ゲームを終了します');
      }
    }
  </script>

フォーム入力されたら、room.htmlに入室できるようaction=room.htmlとします。
更に、フォームのname(サーバーに送られたときにデータベースで判別できるように)を付けます。
フォームイベントと同時にJSが発動してほしいので、id="log"とします。

JS側の実装を行っていきます。
document.getElementByIdでHTML側でセットしたidを取得します。
更にイベントを設定するため、onsubmitにfunctionを代入します。
そして、テスト用のためにconsole.logで送信確認を行います。

今回は、ユーザーに入力の有無を問うため、window.confirmで入室するか聞きます。
ここでif文で、条件分岐を実施します。

最後に、実際に処理が実施されているのか確認したいので、ページ変移を防ぐため、functionパラメータにeventを引き渡します。
event.preventDefaultメソッドを追加します。
そうすることで、イベントが終わった後にログにconsole処理がされているか確認することができました。

*追記
やりたいこと▶confirmで入室を問うた後にいいえなら終了、はいなら入室。

index.html
 <script>
    document.getElementById('log').onsubmit = function() {
      // event.preventDefault();
      console.log('送信');
      const answer = window.confirm('入室しますか?');
      if (answer === true) {
        console.log('ゲームを初めます');
      } else {
        window.alert('終了します');
      }
    }

    </script>

定数answerにwindow.confirmを代入(保存)。
条件分岐で、answerがtrueなら入室 実行可能
falseならアラートが出て終了 アラートは出たが、okボタンを押すとページが変移してしまった。

考えたこと▶ページ変移の記述をif文内で行うべきなのか?
実施後▶window.location.href記述したが、ページ変移しなかった。

0
2
0

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
0
2