Storing form field data in cookies (приклад зберігання даних полів форми в куках)

Last update: 22 Квітня, 2023

Category: Form, PHP code examples

Кусочек верстки формы

<h2>Add a company overview to make it easier for investors to evaluate it. You can include a description of the business model, structure of the company, and its products and services</h2>
<div class="inputs">
    <div class="input-wrap">
        <label for="gvidado">
            <span>Who is in your company's leadership and how does their experience contribute to the company's success?</span>
            <textarea class="req-field hint" name="gvidado" id="gvidado" placeholder="Your text..." type="text"></textarea>
        </label>
    </div>
    <div class="input-wrap">
        <label for="produkto">
            <span>What customer need is your product or service addressing?</span>
            <textarea class="req-field hint" name="produkto" id="produkto" placeholder="Your text..." type="text"></textarea>
        </label>
    </div>
    <div class="input-wrap">
        <label for="merkato">
            <span>Describe the geographic, demographic, and psychographic characteristics of the target market.</span>
            <textarea class="req-field hint" name="merkato" id="merkato" placeholder="Your text..." type="text"></textarea>
        </label>
    </div>
    <div class="input-wrap">
        <label for="klientoj">
            <span>Specify who your customers are and why you target them.</span>
            <textarea class="req-field hint" name="klientoj" id="klientoj" placeholder="Your text..." type="text"></textarea>
        </label>
    </div>
    <div class="input-wrap">
        <label for="strategio">
            <span>What strategy will you use to build, market and maintain company value.</span>
            <textarea class="req-field hint" name="strategio" id="strategio" placeholder="Your text..." type="text"></textarea>
        </label>
    </div>
    <div class="input-wrap">
        <label for="avantagojn">
            <span>What competitive advantages does your company have (for example, manufacturing processes, patents, inventor's advantage, high competence or unique technology)?</span>
            <textarea class="req-field hint" name="avantagojn" id="avantagojn" placeholder="Your text..." type="text"></textarea>
        </label>
    </div>
    <div class="input-wrap">
        <label for="profitojn">
            <span>Describe the products and services, indicating the main benefits from the customer's point of view.</span>
            <textarea class="req-field hint" name="profitojn" id="profitojn" placeholder="Your text..." type="text"></textarea>
        </label>
    </div>
    <div class="input-wrap">
        <label for="altiri">
            <span>What strategy do you intend to apply to attract and retain customers? How are you going to promote and sell and build customer loyalty for your market offering?</span>
            <textarea class="req-field hint" name="altiri" id="altiri" placeholder="Your text..." type="text"></textarea>
        </label>
    </div>
</div>

Скрипт JS

$(document).ready(function () {
    // селектор для формы(просто как часть кода, не обязателен)
    function Selector () {
        $('.dropdown').click(function () {
            $(this).attr('tabindex', 1).focus();
            $(this).toggleClass('active');
            $(this).find('.dropdown-menu').slideToggle(300);
        });

        $('.dropdown').focusout(function () {
            $(this).removeClass('active');
            $(this).find('.dropdown-menu').slideUp(300);
        });

        $('.dropdown .dropdown-menu li').click(function () {
            $(this).parents('.dropdown').find('span').text($(this).text());
            $(this).parents('.dropdown').find('input').attr('value', $(this).text());
        });

        $('.dropdown-menu li').click(function () {
          var input = '<strong>' + $(this).parents('.dropdown').find('input').val() + '</strong>';
        });
    };
    // Меню для мобильного устройства
    $("#menu-btn").click(function(){
        if ($(this).hasClass("open-menu")) {
            $(this).addClass("close-menu");
            $(this).removeClass("open-menu");
            $("#menu").toggleClass("menu-show");
            $("body").addClass("no-scroll");
            $(".over").addClass("over-show");

        } else if ($(this).hasClass("close-menu")) {
            $(this).addClass("open-menu");
            $(this).removeClass("close-menu");
            $("#menu").toggleClass("menu-show");
            $("body").removeClass("no-scroll");
            $(".over").removeClass("over-show");
        }
    });
    // Функция по установке куки. Передаем сюда имя куки.
    function getCookie(name) {
        let matches = document.cookie.match(new RegExp(
          "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
        ));
        return matches ? decodeURIComponent(matches[1]) : undefined;
    }
    function setCookie(name, value) {
        options = {
            path: '/',
            secure: true,
            'max-age': 3600,
            'domain' : '.idma2.xyz'
        };
        if (options.expires instanceof Date) {
            options.expires = options.expires.toUTCString();
        }
        let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
        for (let optionKey in options) {
            updatedCookie += "; " + optionKey;
            let optionValue = options[optionKey];
            if (optionValue !== true) {
                updatedCookie += "=" + optionValue;
            }
        }
        document.cookie = updatedCookie;
    }
    
    //Функция по востановлению данных из куки в текстовые поля.
    function Data () {
        $("textarea, input").each(function(index){
            let info = $(this).attr("name");
            let data = getCookie(info);
            if(data !== "" || data !=="undefined") {
                $(this).val(data);
            }
        });
    }
    //Функция по установке куки при потери фокуса поля.
    $("textarea, input").focusout(function(){
        let name = $(this).attr("name");
        let value = $(this).val();
        let current = getCookie(name);
        setCookie(name, value);
    });
    
    //Функция которая проверяет форму на пустые поля(в данном примере все поля должны быть заполненными)
    let display;
    $("form").on("submit", function(){
        let form = $(this);
        form.find('.req-field').each(function () {
            let value = $(this).val(),
                inval = $(this).attr("value"),
                line = $(this).closest('.hint');
            if(!value || inval === "") {                  
                line.addClass('error');
                setTimeout(function() {
                  line.removeClass('error');
                }.bind(this),2000);
                event.preventDefault();
            }
        });
    });
    // При нажатии на кнопку отправки формы скролим к пустому полю
    $("#send-btn").on("click", function(){
        scrollTo();
    });
    // Сама функция скрола
    function scrollTo() {
        let form = $("form");
        form.find('.req-field').each(function () {
            let value = $(this).val();
            console.log(value);
            if (value === "") {                  
                $('html, body').animate({
                    scrollTop: $(this).offset().top - 100
                }, 1500);
                console.log("???");
                return false;
            };
        });
    }
    //Проверка для одного из полей на ввод только цифр
    $('#petis').bind("change keyup input click", function() {
        if (this.value.match(/[^0-9, +]/g)) {
            this.value = this.value.replace(/[^0-9, +]/g, '');
        } 
    });
    //Вызов самих функций
    Data();
    Selector ();
    
    
});