document.getElementById('start-btn').addEventListener('click', startQuiz); const reviewsSection = document.getElementById('reviews-section'); reviewsSection.style.display = 'none'; const questions = [ { text: 'Вы являетесь гражданином Российской Федерации?', options: ['Да', 'Нет'] }, { text: 'Знали ли Вы, что платформа S - Bugdet Helper помогает получать стабильный доход от крупнейших частных компаний?', options: ['Да, знал', 'Нет, не знал'] }, { text: 'Имеете ли Вы опыт в инвестировании?', options: ['Да, успешно инвестирую', 'Инвестировал ранее', 'Нет, никогда не инвестировал'], image: "./Инвест 2.jpg" }, { text: 'Какой главный финансовый результат вы хотите достичь?', options: ['Увеличить доход', 'Сохранить капитал', 'Научиться управлять деньгами'], image: "./Инвест.jpg" }, { text: 'С какой суммы вы готовы начать инвестировать?', options: ['10 000 - 20 000 рублей', '20 000 - 40 000 рублей', '40 000 - 60 000 рублей'] } ]; let currentQuestionIndex = 0; function startQuiz() { document.getElementById('video-section').style.display = 'none'; document.getElementById('quiz-section').style.display = 'flex'; showQuestion(); } function updateStepIndicator() { const stepIndicator = document.getElementById('step-indicator'); stepIndicator.innerHTML = ''; // Очищаем текущие кружочки const totalSteps = questions.length; for (let i = 0; i < totalSteps; i++) { const circle = document.createElement('div'); circle.classList.add('circle'); if (i < currentQuestionIndex + 1) { circle.classList.add('filled'); // Закрашиваем кружочки до текущего шага } stepIndicator.appendChild(circle); } } function showQuestion() { const questionContainer = document.getElementById('question-container'); questionContainer.innerHTML = ''; // Очищаем контейнер для нового вопроса const question = questions[currentQuestionIndex]; // Контейнер для сообщения об ошибке const errorMessage = document.createElement('p'); errorMessage.id = 'error-message'; errorMessage.style.color = 'red'; errorMessage.style.display = 'none'; // По умолчанию скрыто errorMessage.textContent = 'Предложение доступно только для граждан Российской Федерации.'; questionContainer.appendChild(errorMessage); // Добавляем текст вопроса const questionElement = document.createElement('h2'); questionElement.textContent = question.text; questionContainer.appendChild(questionElement); // Проверяем, есть ли изображение для текущего вопроса if (question.image) { const imageElement = document.createElement('img'); imageElement.src = question.image; // Указываем ссылку на изображение imageElement.alt = 'Иллюстрация к вопросу'; // Альтернативный текст imageElement.classList.add('question-image'); // Класс для стилизации изображения questionContainer.appendChild(imageElement); } // Добавляем варианты ответа question.options.forEach(option => { const optionElement = document.createElement('label'); optionElement.classList.add('option'); const radio = document.createElement('input'); radio.type = 'radio'; radio.name = 'option'; radio.value = option; // Добавляем обработчик для автоматического перехода к следующему вопросу radio.addEventListener('change', () => { if (currentQuestionIndex === 0) { // Проверяем только для первого вопроса if (radio.value === 'Нет') { errorMessage.style.display = 'block'; // Показываем сообщение об ошибке document.getElementById('next-btn').disabled = true; // Блокируем кнопку } else { errorMessage.style.display = 'none'; // Скрываем сообщение document.getElementById('next-btn').disabled = false; // Разблокируем кнопку setTimeout(nextQuestion, 100); // Переход к следующему вопросу с небольшой задержкой enableNextButton(); // Для остальных вопросов включаем кнопку } } else { enableNextButton(); // Для остальных вопросов включаем кнопку setTimeout(nextQuestion, 100); // Переход к следующему вопросу с небольшой задержкой } }); optionElement.appendChild(radio); optionElement.append(option); questionContainer.appendChild(optionElement); }); // Обновляем информацию о текущем шаге document.getElementById('step-info').textContent = `Шаг ${currentQuestionIndex + 1} из ${questions.length}`; document.getElementById('next-btn').disabled = true; // Отключаем кнопку "Далее" при загрузке нового вопроса updateStepIndicator(); // Обновляем индикатор шагов } // Функция для перехода к следующему вопросу function nextQuestion() { if (currentQuestionIndex < questions.length - 1) { currentQuestionIndex++; showQuestion(); } else { endQuiz(); // Заканчиваем опрос, если это был последний вопрос } } function enableNextButton() { document.getElementById('next-btn').disabled = false; // Включаем кнопку "Далее" при выборе опции } document.getElementById('prev-btn').addEventListener('click', () => { if (currentQuestionIndex > 0) { currentQuestionIndex--; showQuestion(); } }); document.getElementById('next-btn').addEventListener('click', () => { if (currentQuestionIndex < questions.length - 1) { currentQuestionIndex++; showQuestion(); } else { endQuiz(); } }); function endQuiz() { document.getElementById('quiz-section').style.display = 'none'; document.getElementById('form-section').style.display = 'flex'; const phoneInput = document.getElementById('phone'); // Автоматически добавляем префикс +7 phoneInput.addEventListener('focus', () => { if (!phoneInput.value.startsWith('+7')) { phoneInput.value = '+7'; } }); // Запрещаем удаление префикса phoneInput.addEventListener('input', () => { if (!phoneInput.value.startsWith('+7')) { phoneInput.value = '+7'; } }); // Удаляем лишние пробелы phoneInput.addEventListener('blur', () => { phoneInput.value = phoneInput.value.trim(); }); } async function showThankYouMessage(event) { event.preventDefault(event); let formValid = true; let errorText = ''; const errorMessage = document.getElementById('error-message-form'); // Проверка каждого поля const name = document.getElementById('name').value.trim(); const surname = document.getElementById('surname').value.trim(); const phone = document.getElementById('phone').value.trim(); const agreement = document.getElementById('agreement').checked; const ageConfirm = document.getElementById('age-confirm').checked; const phonePattern = /^\+7\d{10}$/; // Регулярное выражение для проверки номера if (!phonePattern.test(phone)) { formValid = false; errorText += 'Введите корректный номер телефона в формате +7XXXXXXXXXX'; } if (!name) { formValid = false; errorText += 'Пожалуйста, введите ваше имя. '; } if (!surname) { formValid = false; errorText += 'Пожалуйста, введите вашу фамилию. '; } if (!phone) { formValid = false; errorText += 'Пожалуйста, введите номер телефона. '; } if (!agreement) { formValid = false; errorText += 'Пожалуйста, примите клиентское соглашение. '; } if (!ageConfirm) { formValid = false; errorText += 'Пожалуйста, подтвердите, что вам исполнилось 18 лет. '; } if (!formValid) { errorMessage.textContent = errorText; errorMessage.style.display = 'block'; } else { errorMessage.style.display = 'none'; errorMessage.style.display = 'none'; const formData= new FormData(); formData.append('name', name); formData.append('surname', surname); formData.append('phone2', phone); // Преобразуем FormData в строку const urlEncodedData = new URLSearchParams(); for (const [key, value] of formData.entries()) { urlEncodedData.append(key, value); } try{ document.getElementById('send-form').innerText = 'Отправка...'; document.getElementById('send-form').disabled = true; await fetch('https://script.google.com/macros/s/AKfycbz2uiM0G6eqHJ94PVqxhWHxuZGbqdjAYV67EJtNdZTZ4DA13e_HCvrCT29NKZjdY0Y/exec', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: urlEncodedData.toString(), // Передаем строку, }) } catch(e){ errorMessage.textContent = 'Ошибка!Попробуйте снова'; errorMessage.style.display = 'block'; setTimeout(() => { errorMessage.style.display = 'none' }, 5000); // Переход к следующему вопросу с небольшой задержкой } document.getElementById('send-form').disabled = true; document.getElementById('form-section').style.display = 'none'; document.getElementById('thank-you-section').style.display = 'block'; const reviewsSection = document.getElementById('reviews-section'); reviewsSection.style.display = 'block'; } }