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

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

@ -1767,3 +1767,36 @@ 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) {
jQuery(document).ready(function($) {
$('.form-process, .modal__form-sub').on('submit', function (event) {
event.preventDefault();
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';
}
});
});
let $form = $(this);
let formClass = $form.attr('class');
let action = $form.attr('action');
let formData = $form.serialize();
if (!validateForm(this)) return;
jQuery(document).ready(function($) {
$('.form-process').submit(function(event) {
event.preventDefault();
let validate = validateForm(this);
if (validate){
action = $(this).attr('action')
let formData = $(this).serialize();
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: action,
formData: formData
},
success: function(response) {
closeModals()
showModal('mform-success')
}
});
}
});
$('.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)')
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)');
}
}
});
});
const metaLocale = document.querySelector('meta[property="og:locale"]');
const localeValue = metaLocale.getAttribute('content');
});
const t = window.langData?.translations || {};
// Функция валидации формы
function validateForm(form) {
// Очищаем предыдущие сообщения об ошибках внутри этой формы
clearErrorMessages(form);
let validated = true
// Валидация поля имени
const nameInput = form.querySelector('input[name="name"]');
let validated = true;
const nameInput = form.querySelector('input[name="name"]');
if (nameInput && !nameInput.value.trim()) {
if(localeValue == 'en_US'){
showError(nameInput, 'The name is requeried field');
}
if(localeValue == 'ru_RU'){
showError(nameInput, 'Поле имени обязательно для заполнения.');
}
validated = false
showError(nameInput, t.name_required);
validated = false;
}
// Валидация поля email
const emailInput = form.querySelector('input[name="email"]');
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailInput && !emailPattern.test(emailInput.value.trim())) {
if(localeValue == 'en_US'){
showError(emailInput, 'Email is incorrect.');
}
if(localeValue == 'ru_RU'){
showError(emailInput, 'Введите корректный email.');
}
validated = false
showError(emailInput, t.email_invalid);
validated = false;
}
// Валидация поля телефона
const phoneInput = form.querySelector('input[name="phone"]');
const phonePattern = /^\+?\d{10,15}$/;
if (phoneInput && !phonePattern.test(phoneInput.value.trim())) {
if(localeValue == 'en_US'){
showError(phoneInput, 'The phone is incorrect.');
}
if(localeValue == 'ru_RU'){
showError(phoneInput, 'Введите корректный номер телефона.');
showError(phoneInput, t.phone_invalid);
validated = false;
}
validated = false
}
return validated
return validated;
}
// Функция для отображения сообщения об ошибке
function showError(input, message) {
const errorMessage = document.createElement('div');

@ -3,7 +3,7 @@ modalOpen('.button--filter', '.modal__filter');
modalOpen('.basket-open', '.modal__basket');
modalOpen('.open-to-know', '.modal__to-know');
modalOpen('.login-open', '.modal__login');
modalClose('.modal__close');
modalClose('.modal__close, .m__close');
let modal = document.querySelector('.modal');
@ -98,3 +98,59 @@ window.addEventListener('resize', () => {
jQuery('[data-pname]').on('click', function(){
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