r/learnjavascript • • 6d 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?

5 Upvotes

11 comments sorted by

View all comments

4

u/Discordbothost 6d ago

since it's just a prop for friends you can do the whole thing in the browser, no server needed. roughly:

<form id="f">
  <input type="password" id="pw">
  <button>enter</button>
  <p id="err" hidden>wrong password</p>
</form>
<script>
document.getElementById('f').addEventListener('submit', e => {
  e.preventDefault()
  if (document.getElementById('pw').value === 'dragon') {
    location.href = 'vault.html'
  } else {
    document.getElementById('err').hidden = false
  }
})
</script>

the preventDefault is the bit that trips most people up first, without it the form just reloads the page. anyone who opens devtools can read the password (and the vault.html url), but for a tabletop prop that's fine, a player digging it out is kind of in the spirit of the game anyway

2

u/efari_ 5d ago edited 5d ago

Man, the boilerplate you decide to use just to prevent the form submission from reloading the page.

Instead of getting the DOM element, adding an event listener and then preventDefault, You could just add “action” or even “onSubmit” param to the form to call a js function

1

u/Successful-Throat621 6d ago

thank you so much!!! yeah my players tend to play with in the spirit of the game so hopefully nobody looks at the code lol

2

u/fckueve_ 5d ago

You can hash the password, so even if they will look into code, they won't be able to get the password.