2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

contact form7で、プラグインを使わず、確認画面を出す方法(JavaScript)

Posted at

#contact form7で、プラグインを使わず、確認画面を出す方法(JavaScript)
前回のこの記事をJavaScriptにしました。
https://qiita.com/WebDesignGaju/items/95fd5882c2b2b026ff5c

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!DOCTYPE html>
    <html lang="ja">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Contact Form - Vanilla JS</title>
        <style>
            /*確認画面と完了画面を非表示*/
            .confirm_area,
            .thanks_area {
                display: none;
            }

            /*デフォルトのサンクスメッセージを非表示*/
            .wpcf7-response-output {
                display: none;
            }

            /* エラーメッセージのスタイル */
            .error-message {
                color: #ff0000;
                font-size: 0.8em;
                margin-top: 5px;
                display: none;
            }

            /* フォームの基本スタイル */
            .input_area,
            .confirm_area,
            .thanks_area {
                max-width: 600px;
                margin: 20px auto;
                padding: 20px;
                border: 1px solid #ddd;
                border-radius: 5px;
            }

            label {
                display: block;
                margin: 15px 0 5px;
                font-weight: bold;
            }

            input,
            select,
            textarea {
                width: 100%;
                padding: 8px;
                margin: 5px 0;
                border: 1px solid #ccc;
                border-radius: 3px;
                box-sizing: border-box;
            }

            input[type="radio"] {
                width: auto;
                margin: 0 5px 0 0;
            }

            button {
                background: #007cba;
                color: white;
                padding: 10px 20px;
                border: none;
                border-radius: 3px;
                cursor: pointer;
                margin: 10px 5px 0 0;
            }

            button:disabled {
                background: #ccc;
                cursor: not-allowed;
            }

            button:hover:not(:disabled) {
                background: #005a87;
            }

            .confirm_area span {
                font-weight: normal;
                display: block;
                margin: 5px 0 15px 0;
                padding: 5px;
                background: #f9f9f9;
                border-left: 3px solid #007cba;
            }

            input[type="checkbox"] {
                width: auto;
                margin: 0 5px 0 0;
            }

            .thanks_area {
                transition: opacity .5s ease;
            }
        </style>
    </head>

    <body>

        <!-- 入力画面 -->
        <div class="input_area">
            <h2>お問い合わせフォーム</h2>

            <label>お問合せ種別</label>
            <div id="category">
                <label><input type="checkbox" name="category" value="お仕事のご相談" checked> お仕事のご相談</label>
                <label><input type="checkbox" name="category" value="求人について"> 求人について</label>
                <label><input type="checkbox" name="category" value="その他"> その他</label>
            </div>

            <label>氏名必須</label>
            <input type="text" id="uname" aria-required="true">

            <label>メールアドレス必須</label>
            <input type="email" id="email" aria-required="true">
            <p class="error-message" id="email-error"></p>

            <label>メールアドレス確認用)(必須</label>
            <input type="email" id="email_confirm" aria-required="true">
            <p class="error-message" id="email-match-error">メールアドレスが一致していません</p>

            <label>お住まい必須</label>
            <select id="address" aria-required="true">
                <option value="">選択してください</option>
                <option value="北海道">北海道</option>
                <option value="青森県">青森県</option>
                <option value="秋田県">秋田県</option>
                <option value="岩手県">岩手県</option>
                <option value="宮城県">宮城県</option>
                <option value="新潟県">新潟県</option>
            </select>

            <label>生年月日</label>
            <input type="date" id="date" min="1980-01-01">

            <label>性別</label>
            <div id="gender">
                <label><input type="radio" name="gender" value="女性" checked> 女性</label>
                <label><input type="radio" name="gender" value="男性"> 男性</label>
            </div>

            <label>メッセージ本文</label>
            <textarea id="content" rows="5"></textarea>

            <button type="button" class="confirm_button" disabled>確認する</button>
        </div>

        <!-- 確認画面 -->
        <div class="confirm_area">
            <h2>入力内容確認</h2>
            <p>以下の内容でよろしいですか</p>

            <strong>お問合せ種別</strong><span class="confirm_category"></span>
            <strong>氏名</strong><span class="confirm_uname"></span>
            <strong>メールアドレス</strong><span class="confirm_email"></span>
            <strong>お住まい</strong><span class="confirm_address"></span>
            <strong>生年月日</strong><span class="confirm_date"></span>
            <strong>性別</strong><span class="confirm_gender"></span>
            <strong>メッセージ本文</strong><span class="confirm_content"></span>

            <button type="submit" class="submit_button">送信</button>
            <button type="button" class="back_button">戻る</button>
        </div>

        <!-- 完了画面 -->
        <div class="thanks_area">
            <h2>送信完了</h2>
            <p>お問合せいただきありがとうございました<br>
                2営業日以内に担当者よりご返信差し上げます</p>
        </div>

        <script>
            document.addEventListener("DOMContentLoaded", function () {
                let val;
                let id;
                let radio;
                let check;
                let type;
                let emailMatch = false;

                const change_events = ["keydown", "keyup", "keypress", "change"];
                const items_radio = document.querySelectorAll("[type='radio']:checked");
                items_radio.forEach(function (element, index) {
                    radio = element.value;
                    id = element.closest("[id]").id;
                    document.querySelector('.confirm_' + id).textContent = radio;
                })

                const items_checkbox = document.querySelectorAll("[type='checkbox']:checked");
                items_checkbox.forEach(function (element, index) {
                    check = element.value;
                    id = element.closest("[id]").id;
                    document.querySelector('.confirm_' + id).textContent = check;
                })

                function validateEmails() {
                    const email = document.querySelector("#email").value;
                    const emailConfirm = document.querySelector("#email_confirm").value;

                    if (email !== "" && emailConfirm !== "") {
                        if (email !== emailConfirm) {
                            document.querySelector("#email-match-error").style.display = "block";
                            emailMatch = false;
                        } else {
                            document.querySelector("#email-match-error").style.display = "none";
                            emailMatch = true;
                        }

                    } else {
                        document.querySelector("#email-match-error").style.display = "none";
                        emailMatch = false;
                    }

                    checkRequiredFields();
                }

                const mail_match_fileds = ["#email", "#email_confirm"];

                mail_match_fileds.forEach(function (selector) {
                    const mail_element = document.querySelector(selector);
                    change_events.forEach(function (event) {
                        mail_element.addEventListener(event, validateEmails);
                    })
                })

                const input_elements = document.querySelectorAll(".input_area input, .input_area select, .input_area textarea");
                input_elements.forEach(function (element, index) {
                    element.addEventListener('change', function (e) {
                        val = this.value;
                        type = this.getAttribute("type");
                        if (type == "radio") {
                            radio = this.value;
                            id = this.closest("[id]").id;
                            document.querySelector(".confirm_" + id).textContent = radio;
                        }
                        else if (type == "checkbox") {
                            check = this.value;
                            id = this.closest("[id]").id;
                            let check_item = document.querySelector(".confirm_" + id);
                            if (this.checked) {
                                check_item.textContent += check + " / ";
                            } else {
                                check_item.textContent = check_item.textContent.replace(check + " / ", "");
                            }
                        }
                        else {
                            id = this.getAttribute("id");
                            if (id !== "email_confirm") {
                                const other_val = this.value;
                                let other_item = document.querySelector(".confirm_" + id);
                                other_item.textContent = (other_val) ? other_val : "";
                            }
                        }
                    })
                })

                document.querySelector(".confirm_button").addEventListener("click", function () {
                    document.querySelector(".input_area").style.display = "none";
                    document.querySelector(".confirm_area").style.display = "block";
                    window.scrollTo({
                        top: document.querySelector("#main").scrollY,
                        behavior: "smooth"
                    })
                })

                document.querySelector(".back_button").addEventListener("click", function () {
                    document.querySelector(".input_area").style.display = "block";
                    document.querySelector(".confirm_area").style.display = "none";
                    window.scrollTo({
                        top: document.querySelector("#main").scrollY,
                        behavior: "smooth"
                    })
                })

                document.querySelector(".submit_button").addEventListener("click", function () {
                    const thanksArea = document.querySelector(".thanks_area");
                    document.querySelector(".confirm_area").style.display = "none";
                    window.scrollTo({
                        top: document.querySelector("#main").scrollY,
                        behavior: "smooth"
                    })
                    fadeIn(thanksArea);
                })

                function fadeIn(el) {
                    el.style.display = "block";
                    el.style.opacity = "0";
                    setTimeout(() => el.style.opacity = "1", 20)
                }

                

                function checkRequiredFields() {
                    const target = document.querySelectorAll('[aria-required="true"]');
                    let flag = true;
                    const confirm_btn = document.querySelector('.confirm_button');
                    target.forEach(function (e) {
                        if (e.value === "") {
                            flag = false;
                        }
                    });
                    //フラグがtrueでメールアドレスも一致していれば確認ボタンを有効。それ以外は無効にする
                    if (flag && emailMatch) {
                        //必須項目すべて入力済みかつメールアドレスが一致していれば有効にする
                        confirm_btn.removeAttribute("disabled");
                    }
                    else {
                        //未入力など漏れがある場合または、メールアドレスが一致していない場合は無効にする
                        confirm_btn.setAttribute("disabled", "");
                    }
                }
                change_events.forEach(event => {
                    const target = document.querySelectorAll('[aria-required="true"]');
                    target.forEach(function (e) {
                        e.addEventListener(event, function () {
                            checkRequiredFields();
                        });
                    });
                });
            });
        </script>

    </body>

    </html>
</body>

</html>

郵便番号

document.addEventListener("DOMContentLoaded", function () {
    let val;
    let id;
    let radio;
    let check;
    let type;
    let emailsMatch = false;
    let postalCodeValidation = false;
    
    // ラジオボタン初期値の取得 以下の記述で全てのラジオボタンの初期値を取得
    const radioChecked = document.querySelectorAll("[type='radio']:checked");
    radioChecked.forEach(function (element, index) {
        radio = element.value;
        id = element.closest("[id]").id;
        document.querySelector(".confirm_" + id).textContent = radio;
    });

    // 郵便番号バリデーション
    function validationPostCode() {
        let postCodeVal = document.querySelector("#zip").value;
        console.log(postCodeVal);
        let regex = /^(?:\d{7}|[0-9]{7})$/;
        if (postCodeVal !== "") {
            if (regex.test(postCodeVal)) {
                document.querySelector("#postal-code-error").style.display = "none";
                postalCodeValidation = true;
            } else {
                document.querySelector("#postal-code-error").style.display = "block";
                postalCodeValidation = false;
            }
        } else {
            document.querySelector("#postal-code-error").style.display = "none";
            postalCodeValidation = false;
        }

        checkRequiredFields();
    }
    
    // 郵便番号フィールドのイベント登録
    const zipField = document.querySelector("#zip");
    if (zipField) {
        const events = ['keydown', 'keyup', 'keypress', 'change'];
        events.forEach(function(event) {
            zipField.addEventListener(event, validationPostCode);
        });
    }

    // メールアドレス一致
    function validateEmails() {
        let email = document.querySelector("#email").value;
        let email_confirm = document.querySelector("#email_confirm").value;

        if (email !== "" && email_confirm !== "") {
            if (email !== email_confirm) {
                document.querySelector("#email-match-error").style.display = "block";
                emailsMatch = false;
            } else {
                document.querySelector("#email-match-error").style.display = "none";
                emailsMatch = true;
            }
        } else {
            document.querySelector("#email-match-error").style.display = "none";
            emailsMatch = false;
        }
        // 必須項目チェックと合わせて確認ボタンの有効/無効を切り替え
        checkRequiredFields();
    }

    // メールアドレスフィールドのイベント登録
    const emailFields = ["#email", "#email_confirm"];
    emailFields.forEach(function(selector) {
        const element = document.querySelector(selector);
        if (element) {
            const events = ['keydown', 'keyup', 'keypress', 'change'];
            events.forEach(function(event) {
                element.addEventListener(event, validateEmails);
            });
        }
    });

    // 入力欄の内容が変わった際の処理 入力した内容が確認画面へ登録される
    const inputElements = document.querySelectorAll(".input_area input, .input_area select, .input_area textarea");
    inputElements.forEach(function (element) {
        element.addEventListener('change', function () {
            val = this.value;
            type = this.getAttribute("type");
            if (type == "radio") {
                radio = this.value;
                id = this.getAttribute("name");
                document.querySelector(".confirm_" + id).textContent = radio;
            }
            else if (type == "checkbox") {
                check = this.value;
                id = this.closest("[id]").id;
                document.querySelector(".confirm_" + id).textContent += check + " / ";
            }
            else {
                id = this.getAttribute("id");
                const confirmElement = document.querySelector(".confirm_" + id);
                if (confirmElement) {
                    confirmElement.textContent = val;
                }
            }
        });
    });

    // 戻るボタンを押した際の処理 入力画面を表示・確認画面を非表示
    const backButton = document.querySelector("[type='button'].back_button");
    if (backButton) {
        backButton.addEventListener("click", function () {
            document.querySelector(".input_area").style.display = "block";
            document.querySelector(".confirm_area").style.display = "none";
            window.scrollTo({ top: 0, behavior: "smooth" });
        });
    }

    // 送信ボタンを押した際の処理 サンクス(完了)画面を表示・確認画面を非表示
    const submitButton = document.querySelector("[type='submit'].submit_button");
    if (submitButton) {
        submitButton.addEventListener("click", function () {
            const thanksArea = document.querySelector(".thanks_area");
            fadeIn(thanksArea, 2000);
            document.querySelector(".confirm_area").style.display = "none";
            window.scrollTo({ top: 0, behavior: "smooth" });
        });
    }

    // fadeIn関数(jQueryのfadeIn相当)
    function fadeIn(element, duration) {
        element.style.display = "block";
        element.style.opacity = "0";
        element.style.transition = `opacity ${duration}ms ease`;
        
        setTimeout(() => {
            element.style.opacity = "1";
        }, 10);
    }

    // 必須項目チェック用 定数の作成
    const target = '[aria-required="true"]';

    // 必須項目の内容が変わった際の処理
    function checkRequiredFields() {
        // 判定用フラグ
        let flag = true;
        const requiredElements = document.querySelectorAll(target);

        // 必須項目をループで1つずつ確認
        requiredElements.forEach(function (element, index) {
            if (element.value === "") {
                flag = false;
            }
        });

        console.log(postalCodeValidation);
        const confirmButton = document.querySelector('.confirm_button');
        
        // フラグがtrueなら確認ボタンを有効。falseなら無効にする
        if (flag && emailsMatch && postalCodeValidation) {
            confirmButton.removeAttribute("disabled");
            
            // 確認ボタンを押した際の処理 入力画面を非表示・確認画面を表示
            // 既存のイベントリスナーを削除して重複を防ぐ
            const newConfirmButton = confirmButton.cloneNode(true);
            confirmButton.parentNode.replaceChild(newConfirmButton, confirmButton);
            
            newConfirmButton.addEventListener("click", function () {
                document.querySelector(".input_area").style.display = "none";
                document.querySelector(".confirm_area").style.display = "block";
                window.scrollTo({ top: 0, behavior: "smooth" });
            });
        }
        else {
            // 未入力など漏れがある場合は無効にする
            confirmButton.setAttribute("disabled", "");
        }
    }

    // 必須項目のイベント登録
    const requiredElements = document.querySelectorAll(target);
    const events = ['keydown', 'keyup', 'keypress', 'change'];
    
    requiredElements.forEach(function(element) {
        events.forEach(function(event) {
            element.addEventListener(event, checkRequiredFields);
        });
    });
});
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?