Сейчас узнаем, какой подарок выпадет именно Вам
Крутите колесо
Как показать скрытое поле по нажатию checkbox в Tilda
Brainstorming for desired perfect Usability
Our design projects are fresh and simple and will benefit your business greatly. Learn more about our work!
Watch Video Overview

Как показать скрытое поле по нажатию checkbox в Tilda

1
Создали форму в ZeroBlock
2
Добавили в неё нужные поля и поле checkbox с именем more-details
3
Добавили код в блок Другое - Т123
Важно, что в коде прописываем названия полей, которые будут скрываться/показываться по галочек.
{name: "phone", required: false}
Также не задаём полям обязательное заполнение. Если нужно сделать поле обязательным, то просто в коде у этого поля ставим
{name: "phone", required: true},
Mo-ti Level Up
Видео инструкции по добавлению кода и работе с Zero Block.
Показываем и скрываем нужное поле при клике на заданный checkbox в форме
Фрагмент видео
Библиотека для примера
<script>
//Имена управляемых  полей и обязательность их заполнения
const FIELD_CONFIG = [
    {name: "phone", required: true} 
];
const checkboxName = 'more-details';

document.addEventListener("DOMContentLoaded", function() {
    function waitForAllForms(callback) {
        const maxWaitTime = 7000;
        const startTime = Date.now();
        
        function isFormReady(form) {
            const checkbox = form.querySelector('input[type="checkbox"][name="'+checkboxName+'"]');
            if (!checkbox) return true;
            
            const fieldNames = FIELD_CONFIG.map(f => f.name);
            let allFieldsProcessed = true;
            
            fieldNames.forEach(fieldName => {
                const fields = form.querySelectorAll(`[name="${fieldName}"]`);
                fields.forEach(field => {
                    if (!field.closest('.t-input-group')) {
                        allFieldsProcessed = false;
                    }
                });
            });
            
            return allFieldsProcessed;
        }
        
        function areAllFormsReady() {
            const forms = document.querySelectorAll('form');
            if (forms.length === 0) return false;
            
            for (let form of forms) {
                if (!isFormReady(form)) return false;
            }
            return true;
        }
        
        if (areAllFormsReady()) {
            callback();
            return;
        }
        
        const observer = new MutationObserver(function(mutations) {
            setTimeout(() => {
                if (areAllFormsReady()) {
                    observer.disconnect();
                    callback();
                } else if (Date.now() - startTime > maxWaitTime) {
                    observer.disconnect();
                    console.warn('Timeout waiting for forms, forcing start');
                    callback();
                }
            }, 100);
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true,
            attributes: true,
            attributeFilter: ['class', 'data-tilda-req']
        });
        
        setTimeout(() => {
            observer.disconnect();
            console.warn('Fallback timeout triggered');
            callback();
        }, maxWaitTime);
    }
    
    waitForAllForms(function() {
        initSmsCheckboxHandler();
    });
    
    function initSmsCheckboxHandler() {
        const CONFIG = {
            fieldNames: FIELD_CONFIG.map(f => f.name),
            checkboxSelector: 'input[type="checkbox"][name="'+checkboxName+'"]',
            fieldGroupClass: '.t-input-group',
            ruleClass: '.js-tilda-rule'
        };
        
        function updateArtboardHeight(trigger) {
            const artboard = trigger.closest('.t396__artboard');
            if (artboard?.getAttribute('data-artboard-heightmode') === 'hug') {
                if (typeof t396__updateAutoHeight === 'function') {
                    t396__updateAutoHeight(artboard);
                }
            }
        }
        
        function isFieldRequired(fieldName) {
            const fieldConfig = FIELD_CONFIG.find(f => f.name === fieldName);
            return fieldConfig ? fieldConfig.required : false;
        }
        
        function setFieldRequired(container, fieldName, isVisible) {
            const rule = container.querySelector(CONFIG.ruleClass);
            if (!rule) return;
            
            const shouldBeRequired = isFieldRequired(fieldName);
            
            if (isVisible && shouldBeRequired) {
                rule.setAttribute('data-tilda-req', '1');
            } else {
                rule.removeAttribute('data-tilda-req');
            }
        }
        
        function clearFieldValues(container) {
            container.querySelectorAll('input, textarea, select').forEach(field => {
                if (field.type === 'checkbox' || field.type === 'radio') {
                    field.checked = false;
                } else {
                    field.value = '';
                }
            });
        }
        
        function handleFormFields(checkbox) {
            const form = checkbox.closest('form');
            if (!form) return;
            
            const isChecked = checkbox.checked;
            
            FIELD_CONFIG.forEach(fieldConfig => {
                const fieldName = fieldConfig.name;
                
                form.querySelectorAll(`[name="${fieldName}"]`).forEach(field => {
                    const group = field.closest(CONFIG.fieldGroupClass);
                    if (!group) return;
                    
                    if (isChecked) {
                        group.classList.remove('hide-group');
                        setFieldRequired(group, fieldName, true);
                    } else {
                        group.classList.add('hide-group');
                        clearFieldValues(group);
                        setFieldRequired(group, fieldName, false);
                    }
                });
            });
            
            updateArtboardHeight(checkbox);
        }
        
        function initCheckbox(checkbox) {
            if (checkbox.disabled) {
                handleFormFields(checkbox);
                return;
            }
            
            handleFormFields(checkbox);
            
            const observer = new MutationObserver(mutations => {
                mutations.forEach(mutation => {
                    if (mutation.attributeName === 'checked') {
                        handleFormFields(checkbox);
                    }
                });
            });
            
            observer.observe(checkbox, {
                attributes: true,
                attributeFilter: ['checked']
            });
            
            checkbox.addEventListener('change', function() {
                handleFormFields(this);
            });
            
            checkbox._smsObserver = observer;
        }
        
        const checkboxes = document.querySelectorAll(CONFIG.checkboxSelector);
        checkboxes.forEach(initCheckbox);
        
    }
});
</script>

<style>
.t-input-group.hide-group {
    display: none !important;
}
</style>
Made on
Tilda