はじめに
この記事では「お問い合わせフォームを作ってみよう」チュートリアルの完成コードを記載しています。
チュートリアルのレベル感を確認したい方や、手っ取り早くこのチュートリアルを終えたい方、コーディングに慣れるために写経したい方などはぜひご活用ください。
なお、チュートリアルの各チャプターは前回のチャプターのコードを修正する箇所があるため、完成コードはチュートリアルの各チャプター毎に記載しているコードとは異なる場合があります。チュートリアルの途中で発生した問題を解決するための参考にはならない可能性があるのでご注意ください。
ディレクトリ構造について
お問い合わせページのディレクトリ構造は以下のようになっています。
sample-site/
├ index.html
├ modal.js
├ style.css
├ validasion.js
ルートディレクトリ名を「 sample-site 」としていますが、チュートリアル内では特に指定していないので任意の名前で問題ありません。
また、ルートディレクトリ直下に各ファイルを置いていますが、気になる方はお好みでフォルダ分けしてください。その際は index.html の head 要素内のパスを適宜修正しましょう。
完成コード
以下は「お問い合わせフォームを作ってみよう」チュートリアルの完成コードです。各チャプターで具体的に解説しているので、意図や意味の分からないところがあればチュートリアルで学習することをオススメします。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>お問い合わせ</title>
<link rel="stylesheet" href="style.css">
<script src="validation.js" defer></script>
<script src="modal.js" defer></script>
</head>
<body>
<header>
<h1>LOGO</h1>
</header>
<main>
<h2>お問い合わせ</h2>
<form id="form" action="" method="GET">
<div class="form-item">
<label for="type" class="form-ttl">お問い合わせの種類</label>
<div class="select-wrap">
<select id="type" name="type">
<option value="learn" selected>ウェブ制作の学び方について</option>
<option value="article">記事の内容について</option>
<option value="site">このサイトの使い方について</option>
<option value="admin">このサイトの管理者について</option>
</select>
</div>
</div>
<div class="form-item">
<label for="name" class="form-ttl">お名前<span class="required">必須</span></label>
<p class="example-txt">例:山田 太郎</p>
<p class="err-msg">お名前を入力してください</p>
<input type="text" id="name" name="name" required>
</div>
<div class="form-item">
<fieldset>
<legend class="form-ttl">性別</legend>
<label for="male"><input type="radio" id="male" name="gender" value="male">男性</label>
<label for="female"><input type="radio" id="female" name="gender" value="female">女性</label>
</fieldset>
</div>
<div class="form-item">
<label for="email" class="form-ttl">メールアドレス<span class="required">必須</span></label>
<p class="example-txt">例:hogehoge@example.com</p>
<p class="err-msg">メールアドレスを入力してください</p>
<input type="mail" id="email" name="email" required>
</div>
<div class="form-item">
<fieldset>
<legend class="form-ttl">学習中の言語</legend>
<label for="html"><input type="checkbox" id="html" name="learning" value="html" checked>HTML</label>
<label for="css"><input type="checkbox" id="css" name="learning" value="css">CSS</label>
<label for="javascript"><input type="checkbox" id="javascript" name="learning" value="javascript">JavaScript</label>
<label for="php"><input type="checkbox" id="php" name="learning" value="php">PHP</label>
</fieldset>
</div>
<div class="form-item">
<label for="content" class="form-ttl">お問い合わせ内容<span class="required">必須</span></label>
<p class="err-msg">お問い合わせ内容を入力してください</p>
<textarea id="content" name="content" rows="20" required></textarea>
</div>
<div class="policy-check-wrap">
<label for="policy-check">
<p class="err-msg">個人情報保護方針に同意してください</p>
<input
type="checkbox"
id="policy-check"
name="policy-check"
required>個人情報保護方針に同意します。
</label>
</div>
<div class="btn-wrap">
<button type="submit" id="confirm" class="primary-btn">入力内容を確認</button>
</div>
</form>
</main>
<div id="modal" class="modal-wrap" role="dialog" aria-hidden="true">
<div class="modal-body">
<h2 class="modal-ttl" tabindex="0">入力内容の確認</h2>
<div class="form-item" tabindex="0">
<p id="type-ttl" class="form-ttl">お問い合わせの種類</p>
<p id="type-confirm"></p>
</div>
<div class="form-item" tabindex="0">
<p class="form-ttl">お名前</p>
<p id="name-confirm"></p>
</div>
<div class="form-item" tabindex="0">
<p class="form-ttl">性別</p>
<p id="gender-confirm"></p>
</div>
<div class="form-item" tabindex="0">
<p class="form-ttl">メールアドレス</p>
<p id="email-confirm"></p>
</div>
<div class="form-item" tabindex="0">
<p class="form-ttl">学習中の言語</p>
<p id="learning-confirm"></p>
</div>
<div class="form-item" tabindex="0">
<p class="form-ttl">お問い合わせ内容</p>
<p id="content-confirm"></p>
</div>
<p class="modal-desc">上記の内容で送信します。<br>よろしければ「お問い合わせ内容を送信」を、<br>修正する場合は「修正する」を<br>クリックしてください。</p>
<div class="btn-wrap">
<button type="button" id="back" class="secondary-btn">修正する</button>
<button type="submit" id="submit" class="primary-btn">お問い合わせ内容を送信</button>
</div>
</div>
</div>
<footer>©copyright.</footer>
</body>
</html>
style.css
@charset "UTF-8";
/* ================
基本設定
================ */
body {
font-family: "Helvetica Neue", "Helvetica", "Hiragino Sans", "Hiragino Kaku Gothic ProN", "Arial", "Yu Gothic", "Meiryo", sans-serif;
background-color: #fefeef;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
* {
margin: 0;
padding: 0;
}
/* ================
ページ全体のスタイル
================ */
header {
padding: .5em 1em;
background-color: #fff;
box-shadow: -5px 1px 5px rgba(0, 0, 0, 0.1);
}
main {
width: calc(100% - 2em);
max-width: 768px;
margin: 0 auto 6em;
}
footer {
text-align: center;
padding: 1em 0;
background-color: #fff;
box-shadow: -5px -1px 5px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
padding: 2em 0;
}
form {
background-color: white;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
padding: 2em 1em;
}
.form-ttl {
font-weight: bold;
display: block;
width: fit-content;
margin-bottom: 0.5em;
}
.form-item {
padding: 1em 0.5em 2em;
}
/* .form-item:not(:first-child) {
border-top: 1px solid #bba;
} */
.form-item {
border-bottom: 1px solid #bba;
}
fieldset label {
font-weight: 500;
}
.required {
font-size: 0.75em;
font-weight: bold;
color: #f03030;
margin-left: 1em;
}
.example-txt {
color: #888;
font-size: 0.875em;
margin-bottom: .5em;
}
.policy-check-wrap {
text-align: center;
margin: 2em 0 3em;
font-size: 0.875em;
}
.btn-wrap {
text-align: center;
}
@media screen and (min-width: 768px) {
main {
width: calc(100% - 4em);
}
form {
padding: 3em;
}
.form-ttl {
font-size: 1.25em;
}
.form-item {
padding: 1em 1em 2em;
}
.policy-check-wrap {
font-size: 1em;
}
}
/* ================
フォーム部品
================ */
/* フォーム部品のリセット */
fieldset,
legend,
button,
select,
input[type="text"],
input[type="email"],
input[type="checkbox"],
input[type="radio"],
textarea {
border: none;
outline: none;
background: none;
appearance: none;
}
button:focus,
select:focus,
input[type="text"]:focus,
input[type="email"]:focus,
input[type="checkbox"]:focus,
input[type="radio"]:focus,
textarea:focus {
outline: none;
}
/* フォーム部品の基本設定 */
select,
option,
input,
textarea {
font-family: "Helvetica Neue", "Helvetica", "Hiragino Sans", "Hiragino Kaku Gothic ProN", "Arial", "Yu Gothic", "Meiryo", sans-serif;
font-size: 1em;
font-weight: 500;
}
textarea {
overflow: auto;
resize: none;
}
label,
input[type="checkbox"],
input[type="radio"],
button {
cursor: pointer;
}
fieldset {
display: flex;
flex-wrap: wrap;
gap: 1em;
}
input[type="text"],
input[type="email"],
textarea {
width: 100%;
}
/* ドロップダウンメニューのスタイル */
select {
border: 1px solid #bba;
border-radius: 0.25em;
padding: 1em 2em 1em 1em;
}
select:focus {
outline: 1px solid #bba;
}
.select-wrap {
position: relative;
width: fit-content;
}
.select-wrap::before {
content: "▼";
position: absolute;
color: #bba;
right: 0.5em;
top: 50%;
transform: translateY(-50%);
}
/* テキストフィールドのスタイル */
input[type="text"],
input[type="email"],
textarea {
border: 1px solid #bba;
border-radius: 0.25em;
padding: 0.5em;
background: #fefeef;
box-shadow: inset 1px 1px 3px #c8c4aa;
}
input[type="text"]:focus,
input[type="email"]:focus,
textarea:focus {
outline: 1px solid #c8c4aa;
background: #fffff2;
}
/* ラジオボタン・チェックボックス
共通ののスタイル */
input[type="radio"],
input[type="checkbox"] {
border: 1px solid #bba;
width: 1.25em;
height: 1.25em;
position: relative;
top: 0.25em;
margin-right: 0.5em;
}
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: 1px solid #bba;
}
/* ラジオボタンのスタイル */
input[type="radio"] {
border-radius: 50%;
}
input[type="radio"]:checked {
border-width: 0.375em;
}
/* チェックボックスのスタイル */
input[type="checkbox"] {
border-radius: 0.25em;
}
input[type="checkbox"]::before {
content: "";
display: block;
position: absolute;
top: -0.125em;
left: 0.375em;
width: 0.5em;
height: 1em;
border-bottom: 0.25em solid #bba;
border-right: 0.125em solid #bba;
border-radius: 0.25em;
transform: rotate(45deg);
visibility: hidden;
}
input[type="checkbox"]:checked::before {
visibility: visible;
}
/* ボタンのスタイル */
button {
padding: 1em 2em;
font-weight: bold;
letter-spacing: 0.05em;
border-radius: .5em;
transition:
color .3s ease,
background-color .3s ease,
outline-color .3s ease;
}
.primary-btn {
background-color: #446;
box-shadow: 1px 1px 3px #446;
color: white;
}
.primary-btn:focus,
.primary-btn:hover {
color: #446;
background-color: white;
outline: 2px solid #446;
}
.secondary-btn {
background-color: #ccd;
box-shadow: 1px 1px 3px #ccd;
color: #333;
}
.secondary-btn:focus,
.secondary-btn:hover {
color: #66a;
background-color: white;
outline: 2px solid #66a;
}
/* エラーメッセージのスタイル */
select {
width: 100%;
}
.select-wrrap {
max-width: fit-content;
}
.policy-check-wrap {
font-size: 1em;
}
.form-item,
.policy-check-wrap {
position: relative;
}
.err-msg {
position: absolute;
left: 2em;
bottom: -0.375em;
color: #f06060;
font-size: 0.875em;
font-weight: bold;
border: 2px solid #f06060;
border-radius: 0.25em;
padding: 0.25em 1em;
background: #fffafa;
display: none;
}
.err-msg.show {
display: block;
}
.err-msg::before {
content: "";
position: absolute;
top: -1em;
left: 0.5em;
border: 0.5em solid transparent;
border-bottom: 0.5em solid #f06060;
}
.err-msg::after {
content: "";
position: absolute;
top: -0.875em;
left: 0.5em;
border: 0.5em solid transparent;
border-bottom: 0.5em solid #FFF;
}
.err-msg.show+input[type="text"],
.err-msg.show+input[type="email"],
.err-msg.show+textarea {
border: 1px solid #f06060;
background: #fffafa;
}
.err-msg.show+input[type="text"]:focus,
.err-msg.show+input[type="email"]:focus,
.err-msg.show+textarea:focus {
border: 1px solid #f06060;
outline: 1px solid #f06060;
background: #fffcfc;
}
.policy-check-wrap .err-msg {
left: 50%;
transform: translateX(-50%);
width: max-content;
bottom: -3em;
}
.policy-check-wrap .err-msg::before,
.policy-check-wrap .err-msg::after {
left: 50%;
transform: translateX(-50%);
}
/* 確認画面 */
.modal-wrap {
position: fixed;
top: 0;
left: 0;
z-index: 10;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .5)
overflow: scroll;
display: none;
}
.modal-wrap.show {
display: grid;
grid-template-columns: 1em 1fr auto 1fr 1em;
grid-template-rows: 1em 1fr auto 1fr 1em;
}
.modal-body {
grid-column: 2 / 5;
grid-row: 3;
justify-self: center;
width: 100%;
max-width: 480px;
background-color: #fff;
padding: 2em 1em 4em;
box-shadow: 1px 1px 3px rgba(0, 0, 0, .1);
}
.modal-ttl {
font-size: 1.25em;
text-align: center;
padding: 0;
}
.modal-desc {
text-align: center;
font-size: 0.875em;
margin-top: 2em;
}
.modal-body .form-item:first-of-type {
margin-top: 1.75em;
border-top: 1px solid #bba;
}
#email-confirm {
word-break: break-all;
}
#learning-confirm {
display: flex;
flex-wrap: wrap;
gap: 1em;
}
#content-confirm {
white-space: pre-wrap;
}
.modal-body .btn-wrap {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 2em;
margin-top: 2em;
}
.modal-body .btn-wrap button {
flex: 1 0;
word-break: keep-all;
}
validation.js
/*
==============
HTML要素の取得
==============
*/
const submitBtn = document.getElementById('submit');
const backBtn = document.getElementById('back');
const confirmBtn = document.getElementById('confirm');
const modal = document.getElementById('modal');
/*
=====================
バリデーションのデータ
=====================
*/
/**
* バリデーションに使用するオブジェクトです。
*/
const validationData = {
name: {
element: document.getElementById('name'),
errMsgs: {
empty: {
pattern: /^.+$/,
errMsg: 'お名前を入力してください'
},
spaceOnly: {
pattern: /^(?!\s+$).+$/,
errMsg: 'スペースのみの入力はできません'
},
noSeparated: {
pattern: /^.+\s.+$/,
errMsg: '姓と名の間にスペースを入れてください'
},
max: {
pattern: /^.{0,30}$/,
errMsg: '30文字以内で入力してください'
},
invalid: {
pattern: /^[ぁ-んァ-ヶ一-龠a-zA-Z\s]+$/,
errMsg: 'ひらがな、カタカナ、漢字、半角英字で入力してください'
}
},
eventListeners: ['blur', 'input']
},
email: {
element: document.getElementById('email'),
errMsgs: {
empty: {
pattern: /^.+$/,
errMsg: 'メールアドレスを入力してください'
},
invalid: {
pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
errMsg: 'メールアドレスの形式が正しくありません'
}
},
eventListeners: ['blur', 'input']
},
content: {
element: document.getElementById('content'),
errMsgs: {
empty: {
pattern: /^[\s\S]+$/,
errMsg: 'お問い合わせ内容を入力してください'
}
},
eventListeners: ['blur', 'input']
},
policyCheck: {
element: document.getElementById('policy-check'),
errMsgs: {
unchecked: {
pattern: /^checked$/,
errMsg: '個人情報保護方針に同意してください'
}
},
eventListeners: ['change']
}
}
/*
==========
関数の定義
==========
*/
/**
* validationDataのプロパティに対してバリデーションを実行し、エラーがある場合にフォームの送信を防ぎます。
* @returns {boolean} - バリデーションが成功した場合は true、エラーがある場合は false
*/
function execValidateAll() {
for (const key in validationData) {
if (!validate(validationData[key])) {
return false;
}
}
return true;
}
/**
* validationDataのプロパティに対してvalidation関数を実行するためのイベントを設定します。
* @param {Object} data - バリデーションデータオブジェクト
*/
function setValidateListeners(data) {
for (const key in data) {
const target = data[key];
const element = target.element;
const eventListeners = target.eventListeners;
for (const eventType in eventListeners) {
if (eventListeners[eventType] === 'input') {
continue;
} else {
element.addEventListener(eventListeners[eventType], function () {
validate(target);
});
}
}
}
}
/**
* 入力フィールドの値をバリデーションします。
* @param {Object} target - validationDataのプロパティ
* @returns {boolean} - バリデーションが成功した場合は true、エラーがある場合は false
*/
function validate(target) {
let element = target.element;
let errMsgs = target.errMsgs;
let eventListeners = target.eventListeners;
let value;
if (element.type === 'checkbox') {
value = element.checked ? 'checked' : '';
} else {
value = element.value;
}
let errMsgElem = element.previousElementSibling;
for (const key in errMsgs) {
const { pattern, errMsg } = errMsgs[key];
if (!pattern.test(value)) {
errMsgElem.textContent = errMsg;
errMsgElem.classList.add('show');
element.focus();
if (eventListeners.includes('input')) {
if (!target.inputListener) {
element.addEventListener('input', function () {
validate(target);
});
target.inputListener = true;
}
}
return false;
}
}
errMsgElem.classList.remove('show');
return true;
}
/*
===========================
イベントハンドラの設定
===========================
*/
confirmBtn.addEventListener('click', function(event) {
event.preventDefault();
if (execValidateAll()) {
showConfirm();
};
});
setValidateListeners(validationData);
modal.js
/**
* 確認画面モーダルを表示します。
*/
function showConfirm() {
/**
* フォームの確認データ
* @type {Object.<string, { insert: HTMLElement, value: string }>}
*/
const confirmData = {
type: {
insert: document.getElementById('type-confirm'),
value: document.getElementById('type').options[document.getElementById('type').selectedIndex].text,
},
name: {
insert: document.getElementById('name-confirm'),
value: document.getElementById('name').value,
},
gender: {
insert: document.getElementById('gender-confirm'),
value: getLabels(document.querySelectorAll('input[name=gender]:checked')),
},
email: {
insert: document.getElementById('email-confirm'),
value: document.getElementById('email').value,
},
learning: {
insert: document.getElementById('learning-confirm'),
value: getLabels(document.querySelectorAll('input[name=learning]:checked')),
},
content: {
insert: document.getElementById('content-confirm'),
value: document.getElementById('content').value,
}
}
insertValue(confirmData);
openModal(modal, submitBtn);
if ('hasClickEvent' in backBtn === false) {
backBtn.hasClickEvent = true;
backBtn.addEventListener('click', function () {
closeModal(modal, submitBtn);
});
}
}
/**
* モーダルを表示します。
* @param {HTMLElement} modal - モーダル要素
* @param {HTMLElement} submitBtn - 送信ボタン要素
*/
function openModal(modal, submitBtn) {
modal.classList.add('show');
document.body.style.overflow = 'hidden';
submitBtn.setAttribute('form', 'form');
// アクセシビリティ対策
if (modal.getAttribute('aria-hidden') === 'true') {
modal.ariaHidden = 'false';
}
document.querySelectorAll('body *:not(#modal, #modal *)').forEach(function (element) {
element.setAttribute('aria-hidden', 'true');
});
modal.querySelector('.modal-ttl').focus();
}
/**
* モーダルを非表示にします。
* @param {HTMLElement} modal - モーダル要素
* @param {HTMLElement} submitBtn - 送信ボタン要素
*/
function closeModal(modal, submitBtn) {
modal.classList.remove('show');
document.body.style.overflow = 'visible';
submitBtn.removeAttribute('form');
// アクセシビリティ対策
if (modal.getAttribute('aria-hidden') === 'false') {
modal.ariaHidden = 'true';
}
document.querySelectorAll('body *:not(#modal, #modal *)').forEach(function (element) {
element.removeAttribute('aria-hidden');
});
confirmBtn.focus();
}
/**
* valueをinsertに指定した要素のinnerHTMLに挿入します。
* @param {Object.<string, { insert: HTMLElement, value: string }>} data - データオブジェクト
*/
function insertValue(data) {
for (const key in data) {
if (data[key].value) {
data[key].insert.innerHTML = data[key].value;
}
}
}
/**
* ラベル要素のテキストを取得し、HTML要素として返します。
* @param {NodeListOf<HTMLInputElement>} targets - 対象の入力要素ノードリスト
* @returns {string} HTML形式のテキスト
*/
function getLabels(targets) {
let result = '';
if (targets.length === 0) {
result = '選択されていません。';
} else {
targets.forEach(function (target) {
const label = document.querySelector('label[for=' + target.id + ']');
const spanElement = document.createElement('span');
spanElement.innerHTML = label.textContent;
result += spanElement.outerHTML;
});
}
return result;
};
/**
* フォーカス可能な要素間を指定された方向に移動する関数。
* @param {Array<HTMLElement>} focusElements - フォーカス可能な要素の配列。
* @param {string} direction - 移動の方向 ('down' または 'up')。
*/
function navigateFocus(focusElements, direction) {
if (focusElements.includes(document.activeElement)) {
const index = focusElements.indexOf(document.activeElement);
const nextIndex = direction === 'down' ? index + 1 : index - 1;
if (nextIndex < 0) {
focusElements[focusElements.length - 1].focus();
} else if (nextIndex > focusElements.length - 1) {
focusElements[0].focus();
} else {
focusElements[nextIndex].focus();
}
}
}
// モーダルウィンドウのキーボード操作
modal.addEventListener('keydown', function (event) {
switch (event.key) {
case 'Escape': {
closeModal(modal, submitBtn);
break;
}
case 'Tab': {
const focusElements = Array.from(modal.querySelectorAll('[tabindex="0"], button'));
event.preventDefault();
if (event.shiftKey) {
navigateFocus(focusElements, 'up');
} else {
navigateFocus(focusElements, 'down');
}
break;
}
}
});
最後に
「お問い合わせフォームを作ってみよう」チュートリアルの完成コードは以上です。
このチュートリアルはウェブ制作初学者向けに作られていますが、スキルレベルは人によって違うかと思います。完成コードを活用して学習や制作に役立てて頂けると幸いです。
