You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

218 lines
7.4 KiB

jQuery( function ($) {
'use strict';
let form = $('.enterwell-prize__form');
let message = $('.enterwell-prize__message');
let inputs = form.find('input[required]');
let receiptNumberInput = $('#receipt_number');
let emailInput = $('#email');
let input = $('.input');
// Check input for value
function inputValueCheck(input) {
if (input.val()) {
input.parent().addClass('has-value');
} else {
input.parent().removeClass('has-value');
}
}
// Full input check
function inputFullCheck(input) {
inputValueCheck(input);
clearError(input);
if (input.attr('id') === 'email') {
checkEmail(input);
inputExistsCheck(input, 'email', 'Email');
}
if (input.attr('id') === 'receipt_number') {
inputExistsCheck(input, 'receipt_number', 'Broj računa');
}
}
// Loop through all the input elements on the page for initial values
inputs.each(function() {
inputFullCheck($(this));
});
// Checking for value on input for floating label
input.on('input', function() {
inputValueCheck($(this));
});
// Full check of input every time input loses focus
input.on('blur', function() {
inputFullCheck($(this));
});
// Prevent non numbers, excluding keycodes: backspace (8), tab (9), left arrow (37), right arrow (39), and delete (46)
$('input[type="number"]').on('keydown', function(event) {
if (event.keyCode !== 8 && event.keyCode !== 9 && event.keyCode !== 37 && event.keyCode !== 39 && event.keyCode !== 46 && (event.keyCode < 48 || event.keyCode > 57)) {
event.preventDefault();
}
});
// Country selector
$('#country').countrySelect({
defaultCountry: 'hr',
preferredCountries: ['hr', 'si', 'hu', 'ba', 'rs', 'it'],
localizedCountries: {
'hr': 'Hrvatska',
'si': 'Slovenija',
'hu': 'Mađarska',
'ba': 'Bosna i Hercegovina',
'rs': 'Srbija',
'it': 'Italija'
},
responsiveDropdown: true
});
// Clearing input errors
function clearError(input) {
input.removeClass('has-error invalid');
input.parent().find('.error-message').remove()
}
// Adding error to input
function addError(input, classNames, message) {
input.addClass(classNames);
let error = $('<div>').addClass('error-message').text(message);
let parent = input.parent('.input-wrap');
if (parent.find('.error-message').length > 0) {
parent.find('.error-message').remove();
}
parent.append(error);
}
// Check for existing value when input lost focus
function inputExistsCheck(input, name, errorMessage) {
let inputValue = input.val();
let apiUrl = '/enterwell/wp-json/enterwell-prize/v1/value-check';
$.ajax({
url: apiUrl,
method: 'POST',
data: { [name]: inputValue }, // bracket notation for dynamically setting the input name as key
success: function(response) {
if (response === 'exists') {
addError(input, 'has-error invalid', `*${errorMessage} je već prijavljen`);
} else {
clearError(input);
if (input.attr('id') === 'email') {
checkEmail(input);
}
}
},
error: function(xhr, status, error) {
console.log('Error:', error);
}
});
}
// Check for email format
function isEmailValid(email) {
let regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
// Email input check
function checkEmail(input) {
let email = input.val();
if(email === '') {
clearError(input);
} else if (!isEmailValid(email)) {
clearError(input);
addError(input, 'has-error invalid', '*Neispravna email adresa');
}
}
// Validate and submit
form.submit(function(event) {
event.preventDefault();
let inputs = form.find('input[required]');
let imageInput = $('.drop-zone__input');
let valid = true;
inputs.each(function() {
let input = $(this);
if (input.val() && !input.hasClass('invalid')) {
clearError(input);
}
if (!input.not(imageInput).val()) {
addError(input, 'has-error', '*Obavezna ispuna polja');
valid = false;
} else {
valid = true;
}
});
// Check if image is uploaded
// Attribute value is added on successful image upload in image-upload-js
if (!imageInput.attr('value')) {
//addError(imageInput, '', '*Obavezna ispuna polja');
let parent = imageInput.parent('.drop-zone');
parent.addClass('empty');
let error = $('<div>').addClass('error-message').text('*Obavezna ispuna polja');
if (parent.parent().find('.error-message').length > 0) {
parent.parent().find('.error-message').remove();
}
parent.parent().append(error);
valid = false;
} else {
valid = true;
}
// Check for errors on receipt number and email fields
if (receiptNumberInput.hasClass('has-error') || emailInput.hasClass('has-error')) {
valid = false;
}
if (!valid) {
return false;
} else {
// Submit form
const formUrl = form.attr('action');
$.post(formUrl, form.serialize())
.done(function () {
form.fadeOut(function () {
formEnd(
'icon icon-success',
'Uspješna prijava',
'Dok čekaš mail potvrde, vrati se i pročitaj zadnji korak na putu do nagrade.',
'OK',
'window.location.reload()'
).hide().fadeIn();
});
})
.fail(function (xhr, textStatus, errorThrown) {
console.log('Error:', errorThrown);
form.fadeOut(function () {
formEnd(
'icon icon-fail',
'Neuspješna prijava',
'Došlo je do greške u komunikaciji. Provjeri svoju internetsku vezu i pokušaj ponovo.',
'Pokušaj ponovno',
'window.location.reload()'
).hide().fadeIn();
});
});
}
});
// Form success and fail container
function formEnd(iconClass, titleText, bodyText, buttonLabel, buttonFunction) {
let wrapper = $('<div>').addClass('message-wrapper');
let icon = $('<span>').addClass(iconClass);
let title = $('<h2>').addClass('message-title').text(titleText);
let body = $('<p>').addClass('message-content').text(bodyText);
let button = $('<button>').addClass('button button-primary').attr('onclick', buttonFunction).text(buttonLabel);
wrapper.append(icon, title, body, button);
message.append(wrapper);
return wrapper;
}
});