水曜日, 12月 24, 2025

Let's start JavaScript 92 
HTMLでパスワード生成

HTMLでパスワード生成させてみました。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>パスワード生成</title>
<style>
body {
  padding: 20px;
max-width: 400px;
margin: auto;
background: black;
color: white;
}

label {
display: block;
margin: 8px 0;
}

input[type="number"] {
width: 60px;
}
</style>
</head>
<body>

<h3>パスワード生成ツール</h3>

<label>
文字数:
<input type="number" id="length" value="12" min="1">
</label>

<label><input type="checkbox" id="upper"
checked> 大文字 (A-Z)</label>
<label><input type="checkbox" id="lower"
checked> 小文字 (a-z)</label>
<label><input type="checkbox" id="number"
checked> 数字 (0-9)</label>
<label><input type="checkbox" id="symbol"
checked> 記号 (!@#$%&* など)</label>

<button onclick="generatePassword()">生成</button>

<h3>生成されたパスワード</h3>
<p id="result" style="font-size: 1.5em; font-weight: bold;"></p>

<script>
function generatePassword() {
const length = document.getElementById("length").value;
let chars = "";

if (document.getElementById("upper").checked) chars +=
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (document.getElementById("lower").checked) chars +=
"abcdefghijklmnopqrstuvwxyz";
if (document.getElementById("number").checked) chars +=
"0123456789";
if (document.getElementById("symbol").checked) chars +=
"!@#$%^&*()_-+=[]{};:,.<>?";
//ここでの記載有無で使用できる記号を制限出来ます。

if (chars === "") {
document.getElementById("result").textContent =
"※ 1種類以上選んでください";
return;
}

let password = "";
for (let i = 0; i < length; i++) {
password +=
            chars.charAt(Math.floor(Math.random() * chars.length));
}

document.getElementById("result").textContent = password;
}
</script>

</body>
</html>

実行直後の画面。値を指定して[生成]で・・・

パスワードが表示されます。このまま[生成]でランダムに再生成します。