Sitemap

Random Password Generator with JavaScript

2 min readJun 21, 2024

--

Press enter or click to view image in full size

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Password Generator</h1>

<label>Password Length:</label>
<input type="number" min="1" max="12" id="lengthInput">

<h2>Include:</h2>
<input type="checkbox" id="lowercaseInclude">
<label>Lower Case</label>

<input type="checkbox" id="uppercaseInclude">
<label>Upper Case</label>

<input type="checkbox" id="numbersInclude">
<label>Numbers</label>

<input type="checkbox" id="symbolsInclude">
<label>Symbols</label>

<br>
<button onclick="generatePassword()">Generate</button>

<p id="passwordOutput"></p>
</div>

<script src="script.js"></script>
</body>
</html>

Get Chamod Dilshan 😎’s stories in your inbox

Join Medium for free to get updates from this writer.

CSS

.container{
margin: auto;
text-align: center;
font-family: sans-serif;
}

input{
font-size: 2em;

}

label{
font-size: 1.2em;
}

button{
padding: 10px 14px;
border: none;
border-radius: 12px;
background-color: hsl(240, 72%, 65%);
margin-top: 20px;
font-size: 1.2em;
color: white;
}

JavaScript

function generatePassword() {
const length = document.getElementById("lengthInput").value;
const includeLowercase = document.getElementById("lowercaseInclude").checked;
const includeUppercase = document.getElementById("uppercaseInclude").checked;
const includeNumbers = document.getElementById("numbersInclude").checked;
const includeSymbols = document.getElementById("symbolsInclude").checked;

const lowercaseChars = "abcdefghijklmnopqrstuvwxyz";
const uppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numberChars = "0123456789";
const symbolChars = "!@#$%^&*()<>/;'[]{}~`-=";

let allowedChars = "";
let password = "";

if (includeLowercase) allowedChars += lowercaseChars;
if (includeUppercase) allowedChars += uppercaseChars;
if (includeNumbers) allowedChars += numberChars;
if (includeSymbols) allowedChars += symbolChars;

if (length <= 0) {
document.getElementById("passwordOutput").innerText = "Password length must be at least 1";
return;
}
if (allowedChars.length === 0) {
document.getElementById("passwordOutput").innerText = "At least one set of characters is required";
return;
}

for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * allowedChars.length);
password += allowedChars[randomIndex];
}

document.getElementById("passwordOutput").innerText = `Generated Password: ${password}`;
}

Source — Bro Code Youtube Channel

--

--

Chamod Dilshan 😎
Chamod Dilshan 😎

Written by Chamod Dilshan 😎

I'm Chamod Dilshan! 🚀 Entrepreneur 🚀 ICT undergrad, web dev, and tech enthusiast. Wordsmith on the side. Let's explore tech together