9.1 フォームの主要なイベント
フォームの機能を確保するには、ユーザーがフォームの要素と対話する際に発生するイベントを理解し、それを管理することが必要だよ。以下に、HTMLにおける主要なフォームイベント、それらをJavaScriptで処理する方法、その使用例について詳しく説明するね。
HTMLのフォームは、ユーザーが入力フィールド、ボタン、チェックボックス、ラジオボタンなどのフォーム要素と対話する際に発生するさまざまなイベントを生成することができる。主なフォームイベントには、以下のものが含まれるよ:
- submit — フォーム送信イベント
- reset — フォームリセットイベント
- focus — 要素がフォーカスを受けたときのイベント
- blur — 要素がフォーカスを失ったときのイベント
- change — フォーム要素の値が変化したときのイベント
- input — フォーム要素へのデータ入力イベント
- select — フォーム要素内のテキスト選択イベント
9.2 submitイベント
submitイベントは、フォームが送信されるときに発生するよ。通常、これはユーザーがフォームの「Submit」ボタンを押したときに起こる。このイベントを処理することで、サーバーに送信する前にデータの検証を行ったり、入力エラーがある場合にフォームの送信を防ぐなどのアクションを実行することができるんだ。
submitイベントの処理例:
<form id="my-form" action="/submit" method="post">
<label for="username">ユーザー名:</label>
<input type="text" id="username" name="username">
<button type="submit">送信</button>
</form>
const form = document.getElementById('my-form');
form.addEventListener('submit', function(event) {
const username = document.getElementById('username').value;
if (username === '') {
alert('ユーザー名を入力してください。');
event.preventDefault(); // フォームの送信を防ぐ
} else {
alert(`ユーザー名を取得しました: ${username}`);
event.preventDefault();
}
});
const form = document.getElementById('my-form');
form.addEventListener('submit', function(event) {
const username = document.getElementById('username').value;
if (username === '') {
alert('ユーザー名を入力してください。');
event.preventDefault(); // フォームの送信を防ぐ
}
});
9.3 resetイベント
resetイベントは、フォームが元の状態にリセットされるときに発生するよ。通常、これはユーザーが「Reset」ボタンを押したときに起こる。このイベントを処理することで、エラーメッセージのクリアなどの追加アクションを実行することができるんだ。
resetイベントの処理例:
<div style="min-height: 220px">
<form id="my-form">
<label for="name">Name:</label>
<br>
<input type="text" id="name" name="name">
<br><br>
<label for="email">Email:</label>
<br>
<input type="email" id="email" name="email">
<br><br>
<label for="password">Password:</label>
<br>
<input type="password" id="password" name="password">
<div style="margin-top: 10px">
<button id="btn" type="button">リセット</button>
</div>
</form>
<p id="log"></p>
</div>
<form id="my-form">
<label for="name">Name:</label>
<br>
<input type="text" id="name" name="name">
<br><br>
<label for="email">Email:</label>
<br>
<input type="email" id="email" name="email">
<br><br>
<label for="password">Password:</label>
<br>
<input type="password" id="password" name="password">
<div style="margin-top: 10px">
<button type="reset">リセット</button>
</div>
</form>
<p id="log"></p>
const form = document.getElementById('my-form');
const btn = document.getElementById('btn');
const n = document.getElementById('name');
const e = document.getElementById('email');
const p = document.getElementById('password');
const log = document.getElementById('log');
document.addEventListener('DOMContentLoaded', () => {
n.value = "John";
e.value = "john@mail.com";
p.value = "qwerty";
});
btn.addEventListener('click', () => {
n.value = "";
e.value = "";
p.value = "";
log.textContent = 'フォームがリセットされました!';
});
const form = document.getElementById('my-form');
const log = document.getElementById('log');
form.addEventListener('reset', function () {
log.textContent = 'フォームがリセットされました!';
});
9.4 focusとblurイベント
focusとblurイベントは、それぞれフォーム要素がフォーカスを取得または喪失したときに発生するイベントだよ。これらのイベントは、ユーザーインターフェースを改善するためによく使われるんだ。例えば、ヒントやエラーメッセージを表示するのに使われることが多いよ。
focusイベントの処理例:
<div style="min-height: 55px">
<form id="my-form">
<label for="username">ユーザー名:</label>
<input type="text" id="username" name="username">
<div id="username-hint" style="display: none;">
このヒントはフィールドにフォーカスしたときに表示されるよ。フォーカスが移動しても表示され続けるよ。
</div>
</form>
</div>
<form id="my-form">
<label for="username">ユーザー名:</label>
<input type="text" id="username" name="username">
<div id="username-hint" style="display: none;">
このヒントはフィールドにフォーカスしたときに表示されるよ。フォーカスが移動しても表示され続けるよ。
</div>
</form>
const form = document.getElementById('my-form');
const usernameInput = document.getElementById('username');
const hint = document.getElementById('username-hint');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
usernameInput.addEventListener('focus', function (event) {
hint.style.display = 'block';
});
const usernameInput = document.getElementById('username');
const hint = document.getElementById('username-hint');
usernameInput.addEventListener('focus', function () {
hint.style.display = 'block';
});
blurイベントの処理例:
<div style="min-height: 55px">
<form id="my-form">
<label for="username">ユーザー名:</label>
<input type="text" id="username" name="username">
<div id="username-error" style="display: none; color: red;">
フォーカスが移動してフィールドが空のままの場合にのみエラーが表示されるよ
</div>
</form>
</div>
<form id="my-form">
<label for="username">ユーザー名:</label>
<input type="text" id="username" name="username">
<div id="username-error" style="display: none; color: red;">
フォーカスが移動してフィールドが空のままの場合にのみエラーが表示されるよ
</div>
</form>
const form = document.getElementById('my-form');
const usernameInput = document.getElementById('username');
const error = document.getElementById('username-error');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
usernameInput.addEventListener('blur', function (event) {
error.style.display = usernameInput.value === '' ? 'block' : 'none';
});
const usernameInput = document.getElementById('username');
const error = document.getElementById('username-error');
usernameInput.addEventListener('blur', function () {
error.style.display = usernameInput.value === '' ? 'block' : 'none';
});
9.5 inputイベント
inputイベントは、フォーム要素の値が変化するたびに発生し、要素がフォーカスを失うかどうかに関係なく発生するよ。このイベントはユーザー入力をリアルタイムで検証するためによく使用されるよ。例えば、リアルタイムの入力検証などに使えるんだ。
inputイベントの処理例:
<html lang="ja">
<head>
<style>
input {
outline: none;
}
.valid {
border-color: green;
}
.invalid {
border-color: red;
}
.wrapper-valid::after {
content: "メールアドレスが有効です";
margin-left: 5px;
color: green;
}
.wrapper-invalid::after {
content: "メールアドレスが無効です";
margin-left: 5px;
color: red;
}
</style>
</head>
<body>
<form id="my-form">
<label for="email">Email:</label>
<div id="wrapper">
<input type="email" id="email" name="email">
</div>
</form>
</body>
</html>
const form = document.getElementById('my-form');
const inputWrapper = document.getElementById('wrapper');
const emailInput = document.getElementById('email');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
emailInput.addEventListener('input', function () {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailPattern.test(emailInput.value)) {
inputWrapper.classList.add('wrapper-valid');
inputWrapper.classList.remove('wrapper-invalid');
emailInput.classList.add('valid');
emailInput.classList.remove('invalid');
} else {
inputWrapper.classList.add('wrapper-invalid');
inputWrapper.classList.remove('wrapper-valid');
emailInput.classList.add('invalid');
emailInput.classList.remove('valid');
}
});
const emailInput = document.getElementById('email');
const inputWrapper = document.getElementById('wrapper');
emailInput.addEventListener('input', function () {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailPattern.test(emailInput.value)) {
emailInput.classList.add('valid');
emailInput.classList.remove('invalid');
} else {
emailInput.classList.add('invalid');
emailInput.classList.remove('valid');
}
});
9.6 selectイベント
selectイベントは、ユーザーがテキスト入力フィールドやテキストエリアなどのフォーム要素でテキストを選択したときに発生するよ。このイベントは、選択されたテキストに対して何らかのアクションを実行するために役立つんだ。例えば、コピーのボタンを表示するなど。
selectイベントの処理例:
<div style="min-height: 55px">
<form id="my-form">
<label for="text-input">テキストを入力してください:</label>
<input type="text" id="text" name="text">
<div id="select-message"></div>
</form>
</div>
<form id="my-form">
<label for="text-input">テキストを入力してください:</label>
<input type="text" id="text" name="text">
<div id="select-message"></div>
</form>
document.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById('my-form');
const textInput = document.getElementById('text');
const selectMessage = document.getElementById('select-message');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
textInput.addEventListener('select', function () {
selectMessage.textContent = 'テキストが選択されました!';
});
});
document.addEventListener('DOMContentLoaded', function () {
const textInput = document.getElementById('text');
const selectMessage = document.getElementById('select-message');
textInput.addEventListener('select', function () {
selectMessage.textContent = 'テキストが選択されました!';
});
});
9.7 changeイベント
changeイベントは、フォーム要素の値が変更され、ユーザーがその要素から離れた(フォーカスを失った)ときに発生するよ。このイベントは、ドロップダウンリストやチェックボックスなどのフォームフィールドの変更を検証するためによく使われるんだ。
changeイベントの処理例:
<form id="my-form">
<label for="color-select">色を選択してください:</label>
<select id="color-select" name="color">
<option value="red">赤</option>
<option value="green">緑</option>
<option value="blue">青</option>
</select>
</form>
document.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById('my-form');
const selectElement = document.getElementById('color-select');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
selectElement.addEventListener('change', function () {
alert('色が選択されました: ' + selectElement.value);
});
});
document.addEventListener('DOMContentLoaded', function () {
const selectElement = document.getElementById('color-select');
selectElement.addEventListener('change', function () {
alert('色が選択されました: ' + selectElement.value);
});
});
GO TO FULL VERSION