r/learnjavascript • • 15d ago

Simple Password input field

Hi all, I've been learning webcoding recently and Ive been wanting to make a website to use as a prop in my tabletop games.

My biggest desire right now is to do a password input where submitting an incorrect input displays an error message, while the correct input provides a redirect to a new page.

Since this will only be for my friends and wont host any private data, I'm not too concerned for heavy security, but most resources online are for actual websites and online security. Whats the best way for me to implement something like this?

6 Upvotes

12 comments sorted by

View all comments

1

u/Both-Tart7460 15d ago edited 1d ago

Sorry for my broken english, not a native speaker! That sounds like a really cool tabletop game prop.

Since this is just for friends around the table and doesn't need real server security, here is a clean single-file HTML + Vanilla JS snippet you can drop straight into an index.html file:

<form id="puzzleForm">
  <input type="password" id="passInput" placeholder="Enter secret code..." required autofocus />
  <button type="submit">Unlock</button>
</form>
<p id="errorMsg" style="color: #ff5555; display: none;">Incorrect passcode! Try again.</p>

<script>
  const SECRET_CODE = "dragon123";
  const form = document.getElementById("puzzleForm");
  const input = document.getElementById("passInput");
  const errorMsg = document.getElementById("errorMsg");

  form.addEventListener("submit", (e) => {
    // 1. Prevents the form from reloading the page immediately
    e.preventDefault();

    // 2. trim() + toLowerCase() avoids annoying mobile keyboard space/caps issues
    if (input.value.trim().toLowerCase() === SECRET_CODE.toLowerCase()) {
      errorMsg.style.display = "none";
      window.location.href = "secret_room.html";
    } else {
      errorMsg.style.display = "block";
      input.value = "";
      input.focus();
    }
  });
</script>

Two small things that tripped me up when I was learning:

  • Always call e.preventDefault(), otherwise submitting <form> reloads the page and hides your error message in 0.1s.
  • .trim() saves players on mobile phones when autocorrect sneaks a trailing space after the word.

Have fun with your tabletop session!

1

u/Successful-Throat621 15d ago

I think the formatting got a little messed up when you pasted this into reddit? I tried putting in my code but i cant seem to clean it up into a way that works

1

u/Both-Tart7460 1d ago

hey so sorry about that! reddit's rich-text editor completely ate my line breaks when i pasted it earlier 😅

i just edited my comment above in markdown mode so the <form> and <script> block is clean and copy-pasteable now. hope your tabletop session goes awesome!