Redirecting to a page named after the entered password?

I am so sorry to have to post here but I really can’t find anything to help me doing what I have in mind. And I apologize in advance if my request is ridiculous.
I would like a password field as well as submit button to be displayed on my website. Let’s call it welcome.html for example. If I click the button without entering anything in the password field I would like to be redirected to welcome.html (same page).
But if I enter 123 in the password field I would like to be redirected to welcome123.html and if I enter 456 in the password field I would like to be redirected to welcome456.html and if I enter 789 in the password field I would like to be redirected to welcome789.html and so on.
Below is the script I already have. It works quite well but there are two issues :
- I’m limited to only one password at a time.
- The password is visible in the page source.
<div align="left">
<form>
<div class="group">
<input type="password" name="password" id="accesspasswd" required>
<span class="highlight"></span>
<span class="bar"></span><IMG SRC="images/padlock.png" WIDTH="100" onclick="onSubmit()">
</div>
</form>
</div>
</punlock>
</div>
<script>
function onSubmit() {
if (document.getElementById('accesspasswd').value == 'MYPASSWORD')
{window.location.href = 'welcomeMYPASSWORD.html'; }
else{window.location.href = 'welcome.html'; }
};
</script>
Can someone help me achieving what I would like to get, please ?
Thank you very much for reading.
Regards.
Answer
Your request is not ridiculous at all!
Here is the refactored version of your code:
trim()
removes accidental spaces.validPasswords
is an array – you can add as many passwords as you want and redirect dynamicallyonsubmit="return onSubmit();" prevents page reload. When a
<form>
is submitted in HTML, the default behavior is:The browser sends the form data (even if there’s no
action
)The page reloads (or navigates to a new page)
If you only used a<button>
or an<img onclick="onSubmit()">
, the form might:Try to submit and reload the page before your JavaScript executes fully
Interfere with your
window.location.href
redirect
<div align="left">
<form onsubmit="return onSubmit();">
<div class="group">
<input type="password" name="password" id="accesspasswd" required />
<button type="submit">Unlock</button>
</div>
</form>
</div>
<script>
function onSubmit() {
const input = document.getElementById('accesspasswd').value.trim();
const validPasswords = ['123', '456', '789'];
if (validPasswords.includes(input)) {
window.location.href = `welcome${input}.html`;
} else {
window.location.href = 'welcome.html';
}
return false; // Prevent form submission
}
</script>
Enjoyed this question?
Check out more content on our blog or follow us on social media.
Browse more questions