Task 6951 | Рефакторинг модулей Form и Popup

pull/36/head
parent f56f54c0c0
commit 826fd48617
  1. 33
      wp-content/themes/cosmopet/global-functions/multilang-functions.php
  2. 176
      wp-content/themes/cosmopet/modules/forms/assets/js/form.js
  3. 60
      wp-content/themes/cosmopet/modules/popup/assets/js/modal.js

@ -1767,3 +1767,36 @@ pll_register_string('Ваш город', 'Ваш город', 'Checkout');
pll_register_string('Оплатить', 'Оплатить', 'Checkout'); pll_register_string('Оплатить', 'Оплатить', 'Checkout');
}); });
// Регистрируем строковые переводы для динамической подстановки в js
add_action('wp_head', function () {
if (function_exists('pll_current_language')) {
$lang = pll_current_language();
$translations = [
'en' => [
'name_required' => 'The name is required.',
'email_invalid' => 'Email is incorrect.',
'phone_invalid' => 'The phone number is incorrect.'
],
'ru' => [
'name_required' => 'Поле имени обязательно для заполнения.',
'email_invalid' => 'Введите корректный email.',
'phone_invalid' => 'Введите корректный номер телефона.'
]
];
$current_translations = $translations[$lang] ?? $translations['en'];
?>
<script>
window.langData = {
currentLang: "<?php echo esc_js($lang); ?>",
translations: <?php echo json_encode($current_translations, JSON_UNESCAPED_UNICODE); ?>
};
</script>
<?php
}
});

@ -1,157 +1,75 @@
// Функция для показа модальных окон
function showModal(modalClass) {
const modal = document.querySelector('.' + modalClass);
if (modal) {
modal.style.display = 'flex';
}
}
// Функция для закрытия модальных окон
function closeModals() {
const modals = document.querySelectorAll('.mform');
modals.forEach(modal => {
modal.style.display = 'none';
});
}
// Инициализация после загрузки DOM
document.addEventListener('DOMContentLoaded', function() {
// Обработчики для кнопок закрытия
const closeButtons = document.querySelectorAll('.close-button');
closeButtons.forEach(button => {
button.addEventListener('click', function() {
closeModals();
});
});
// Закрытие при клике вне контента
window.addEventListener('click', function(event) {
const modals = document.querySelectorAll('.mform');
modals.forEach(modal => {
if (event.target === modal) {
modal.style.display = 'none';
}
});
});
});
// Закрытие при клике вне контента
window.addEventListener('click', function(event) {
const modals = document.querySelectorAll('.modal-success, .modal-offer');
modals.forEach(modal => {
if (event.target === modal) {
modal.style.display = 'none';
}
});
});
jQuery(document).ready(function($) { jQuery(document).ready(function($) {
$('.form-process').submit(function(event) { $('.form-process, .modal__form-sub').on('submit', function (event) {
event.preventDefault(); event.preventDefault();
let validate = validateForm(this);
if (validate){ let $form = $(this);
action = $(this).attr('action') let formClass = $form.attr('class');
let formData = $(this).serialize(); let action = $form.attr('action');
$.ajax({ let formData = $form.serialize();
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: { if (!validateForm(this)) return;
action: action,
formData: formData $.ajax({
}, type: 'POST',
success: function(response) { url: woocommerce_params.ajax_url,
closeModals() data: {
showModal('mform-success') action: action,
formData: formData
} },
}); beforeSend: function () {
// Если нужна специфическая логика перед отправкой
},
success: function (response) {
if ($form.hasClass('form-process')) {
closeModals();
showModal('mform-success');
}
},
complete: function (response) {
if ($form.hasClass('modal__form-sub')) {
let email = $form.find('input[name="email"]').val();
$('.modal__to-know').removeClass('active');
$('#sub-result-email').html(email);
$('.modal__to-know-submit').addClass('active').css('filter', 'blur(0px)');
}
} }
}); });
$('.modal__form-sub').on('submit', function (e) {
e.preventDefault();
var action = $(this).attr('action')
var email = $(this).find('input[name="email"]').val()
var formData = $(this).serialize()
$.ajax({
type: 'post',
url: woocommerce_params.ajax_url,
data: {
action: action,
formData: formData
},
beforeSend: function (response) {
},
complete: function (response) {
$('.modal__to-know').removeClass('active')
$('#sub-result-email').html(email)
$('.modal__to-know-submit').addClass('active').css('filter', 'blur(0px)')
},
success: function (response) {
},
});
});
}); });
const metaLocale = document.querySelector('meta[property="og:locale"]'); });
const localeValue = metaLocale.getAttribute('content');
const t = window.langData?.translations || {};
// Функция валидации формы
function validateForm(form) { function validateForm(form) {
// Очищаем предыдущие сообщения об ошибках внутри этой формы
clearErrorMessages(form); clearErrorMessages(form);
let validated = true let validated = true;
// Валидация поля имени
const nameInput = form.querySelector('input[name="name"]'); const nameInput = form.querySelector('input[name="name"]');
if (nameInput && !nameInput.value.trim()) { if (nameInput && !nameInput.value.trim()) {
if(localeValue == 'en_US'){ showError(nameInput, t.name_required);
showError(nameInput, 'The name is requeried field'); validated = false;
}
if(localeValue == 'ru_RU'){
showError(nameInput, 'Поле имени обязательно для заполнения.');
}
validated = false
} }
// Валидация поля email
const emailInput = form.querySelector('input[name="email"]'); const emailInput = form.querySelector('input[name="email"]');
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailInput && !emailPattern.test(emailInput.value.trim())) { if (emailInput && !emailPattern.test(emailInput.value.trim())) {
showError(emailInput, t.email_invalid);
if(localeValue == 'en_US'){ validated = false;
showError(emailInput, 'Email is incorrect.');
}
if(localeValue == 'ru_RU'){
showError(emailInput, 'Введите корректный email.');
}
validated = false
} }
// Валидация поля телефона
const phoneInput = form.querySelector('input[name="phone"]'); const phoneInput = form.querySelector('input[name="phone"]');
const phonePattern = /^\+?\d{10,15}$/; const phonePattern = /^\+?\d{10,15}$/;
if (phoneInput && !phonePattern.test(phoneInput.value.trim())) { if (phoneInput && !phonePattern.test(phoneInput.value.trim())) {
if(localeValue == 'en_US'){ showError(phoneInput, t.phone_invalid);
showError(phoneInput, 'The phone is incorrect.'); validated = false;
}
if(localeValue == 'ru_RU'){
showError(phoneInput, 'Введите корректный номер телефона.');
}
validated = false
} }
return validated
return validated;
} }
// Функция для отображения сообщения об ошибке // Функция для отображения сообщения об ошибке
function showError(input, message) { function showError(input, message) {
const errorMessage = document.createElement('div'); const errorMessage = document.createElement('div');

@ -3,7 +3,7 @@ modalOpen('.button--filter', '.modal__filter');
modalOpen('.basket-open', '.modal__basket'); modalOpen('.basket-open', '.modal__basket');
modalOpen('.open-to-know', '.modal__to-know'); modalOpen('.open-to-know', '.modal__to-know');
modalOpen('.login-open', '.modal__login'); modalOpen('.login-open', '.modal__login');
modalClose('.modal__close'); modalClose('.modal__close, .m__close');
let modal = document.querySelector('.modal'); let modal = document.querySelector('.modal');
@ -97,4 +97,60 @@ window.addEventListener('resize', () => {
jQuery('[data-pname]').on('click', function(){ jQuery('[data-pname]').on('click', function(){
jQuery('#sub_product_name').val(jQuery(this).data('pname')) jQuery('#sub_product_name').val(jQuery(this).data('pname'))
}) })
// Функция для показа модальных окон
function showModal(modalClass) {
const modal = document.querySelector('.' + modalClass);
if (modal) {
modal.style.display = 'flex';
}
}
//Тут модальные окна которые открываются по другой логике и имеют другую верстку - дальше нужно будет привести к одному виду.
// Функция для закрытия модальных окон
function closeModals() {
const modals = document.querySelectorAll('.mform');
modals.forEach(modal => {
modal.style.display = 'none';
});
}
// Инициализация после загрузки DOM
document.addEventListener('DOMContentLoaded', function() {
// Обработчики для кнопок закрытия
const closeButtons = document.querySelectorAll('.close-button');
closeButtons.forEach(button => {
button.addEventListener('click', function() {
closeModals();
});
});
// Закрытие при клике вне контента
window.addEventListener('click', function(event) {
const modals = document.querySelectorAll('.mform');
modals.forEach(modal => {
if (event.target === modal) {
modal.style.display = 'none';
}
});
});
});
// Закрытие при клике вне контента
window.addEventListener('click', function(event) {
const modals = document.querySelectorAll('.modal-success, .modal-offer');
modals.forEach(modal => {
if (event.target === modal) {
modal.style.display = 'none';
}
});
});
Loading…
Cancel
Save