File: D:/HostingSpaces/BVerhoeven/verhoevendak.nl/wwwroot/js/contact.js
/**
* Created by Pascal on 15/06/16.
*/
$(function () {
//Set to true if we want to send the form via AJAX
var contactFormViaAjax = false;
$('#contactForm').append('<input type="hidden" name="secretCode" value="isHuman" />');
$('#contactForm .submit').click(function () {
//Set the form fields to an object
var formFields = setFormFields();
//console.log(formFields);
//Remove the alert classes
$('.check-alert').removeClass('show');
$('.input-rows .alert').removeClass('alert');
$('.check-alert.temp').remove();
//Validate the fields, and set the send variable
var send = validateFields(formFields);
//If Send is true, Send the contactForm with Ajax
//if (send) sendContactForm(formFields);
//If .submit isn't a input field but an div, p or other html element
if (send && contactFormViaAjax == false){
console.log(formFields);
$('#contactForm').submit();
}
//Stop the form from submitting
return false;
});
});
/**
* A quick ajax validation of the fields
* We only check if certain fields are not empty
*
* @param values
* @returns {boolean}
*/
function validateFields(values) {
//By default the send value is true
var send = true;
//Remove the alert class from the input fields before we validate
$('#contactForm input, #contactForm textarea').removeClass('alert');
//The fields we are going to validate
var fields = ['name', 'email', 'formMessage'];
//Loop trough the fields
$.each(fields, function (index, key) {
//Check the element based on the key is not empty, if true, try next element
if (values[key] != '') return;
//If empty
//Set send to false
send = false;
//Add an alert class to the form element of the key
$('#contactForm #' + key).addClass('alert');
$('#contactForm #' + key).parent().find('.error-message').addClass('active').html('Dit veld is verplicht');
//console.log(key);
});
//Return the send variable
return send
}
/**
* Sent the given formFields with Ajax
*
* @param formFields
*/
function sendContactForm(formFields) {
$.ajax({
//Set method to post
method: "POST",
//Add the formFields
data: formFields,
//Get the url from the action url
url: $('#contactForm').attr('action')
}).done(function (msg) {
//What to do when the form is submitted
//If the return message is not the string "true"
if (msg != 'true') {
// Loop trough the message
for (var key in msg) {
//Set the first message for every key
$('#contactForm .form-element.' + key + ' .error').html(msg[key][0]).addClass('active');
}
console.log(msg);
//Exit the function
return
}
//All was good
//Remove the contactForm
$('#contactForm').remove();
//Show the thanks block
$('.contact-form .thanks').removeClass('inactive');
});
}
/**
* Return an object of form fields
* Add the secretCode.
*
* @returns object
*/
function setFormFields() {
return {
name: $('#contactForm #name').val(),
phone: $('#contactForm #phone').val(),
email: $('#contactForm #email').val(),
formMessage: $('#contactForm #formMessage').val(),
secretCode: 'isHuman'
};
}