Counter of submitted forms in php - javascript

I am trying to make a counter for submitting a form in php, if the data from the forms is sent to the server, +1 is written to the counter.txt file, this data is used to form the header in the letter. Everything works, but 5 identical letters come to the mail, the next time it sends 10 and so on. What is the problem? Why is this happening?
When I remove the counter code everything works fine and one letter arrives.
<?php
$email = ($_POST['sel']);
$change = ($_POST['button-set']);
$name = ($_POST['name']);
$question = ($_POST['message']);
$submit = ($_POST['submit']);
if (isset ($submit)) {
$count = file_get_contents ('counter.txt');
$count ++;
file_put_contents ('counter.txt', $count);
}
else {
$count = file_get_contents ('counter.txt');
};
$to = 'support#archsupport.ru';
$subject = 'Application number: ' . $count . 'from the site archsupport.ru';
$message = 'Name: ' . $name . "\r\n" . 'Contacts: ' . $email . "\r\n" . 'Write ' . $change . "\r\n" . 'Question: ' . $question ;
$headers = 'From: zergg52#gmail.com ' . "\r\n";
$subject = preg_replace("/(\r\n)|(\r)|(\n)/", "", $subject);
$subject = preg_replace("/(\t)/", " ", $subject);
$subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
#mail($to, $subject, $message, $headers);
echo 'message sent!';
var_dump($email,$change,$name,$question,$submit,$count)
?>
Page code:
var form = document.getElementsByTagName('form')[0];
var names = document.getElementById('name');
var validn = document.getElementById('vn');
var iconrequired = document.querySelector('#namereq');
var email = document.getElementById('sellection');
var valids = document.getElementById('vs');
var iconrequireds = document.querySelector('#sellectionreq');
var text = document.getElementById('qestions');
var validt = document.getElementById('vt');
var iconrequiredt = document.querySelector('#textreq');
document.addEventListener('input', function validation() {
var x = document.forms["support"]["sellection"].value;
if (names.validity.valid) {
validn.className = "valid";
iconrequired.className = "iconrequired hide";
};
if (email.validity.valid && x != "") {
valids.className = "valid";
iconrequireds.className = "iconrequired hide";
};
if (text.validity.valid) {
validt.className = "valid";
iconrequiredt.className = "iconrequired hide";
};
if (!names.validity.valid) {
validn.className = "invalid";
iconrequired.className = "iconrequired hide";
};
if (!email.validity.valid) {
valids.className = "invalid";
iconrequireds.className = "iconrequired hide";
};
if (!text.validity.valid) {
validt.className = "invalid";
iconrequiredt.className = "iconrequired hide";
};
if (names.validity.valid && email.validity.valid && text.validity.valid) {
$('#support').submit(function() {
$.post(
'https://www.archsupport.ru/post-email.php',
$("#support").serialize(),
function(msg) {
$('#support').hide('slow');
$('#message').html(msg);
}
);
});
} else {
return false;
}
});
function validateSellection() {
var x = document.forms["support"]["sellection"].value;
if (x === "") {
document.getElementById('sellectionreq').classList.remove("hide");
return false;
} else {
document.getElementById('sellectionreq').classList.add("hide");
return false;
}
};
function validateName() {
var x = document.forms["support"]["name"].value;
if (x === "") {
document.getElementById('namereq').classList.remove("hide");
return false;
} else {
document.getElementById('namereq').classList.add("hide");
return false;
}
};
function validateText() {
var x = document.forms["support"]["qestions"].value;
if (x === "") {
document.getElementById('textreq').classList.remove("hide");
return false;
} else {
document.getElementById('textreq').classList.add("hide");
return false;
}
};
$('#support').submit(function validate() {
if (validateName() && validateSellection() && validateText() === true) {
return false;
} else {
validateSellection();
validateName();
validateText()
return false
}
});
$(".radio").on('click.two', function() {
let input = $("#sellection");
if ($("#radio").prop("checked")) {
input.prop("disabled", false);
input.prop({
"type": "email",
"placeholder": "example#yourmail.ru",
"autocomplete": "email",
"maxlength": "35",
"minlength": "12",
"value": "",
});
document.getElementById("sellection").pattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$";
} else {
input.prop("disabled", false);
$("#sellection").prop({
"type": "tel",
"placeholder": "+7-910-205-46-15",
"autocomplete": "tel",
"maxlength": "16",
"minlength": "11",
"value": "",
});
document.getElementById("sellection").pattern = "\\+7\\s?[\\(]{0,1}9[0-9]{2}[\\)]{0,1}\\s?\\d{3}[-]{0,1}\\d{2}[-]{0,1}\\d{2}";
}
input.focus();
input.val("");
});
var fab = $('.icons');
fab.on('click.ten', function iconback() {
fab.removeClass('checked');
$(this).addClass('checked');
});
#keyframes req {
0% {
transform: translatex(0px);
}
100% {
transform: translatex(5px);
}
}
#keyframes inv {
0% {
opacity: .5;
}
100% {
opacity: 1;
}
}
* {
padding: 0;
margin: 0;
}
:root {
font-family: "HelveticaNeueCyr";
font-weight: 100;
}
form {
font-size: 24px;
position: relative;
width: 100%;
display: inline-flex;
flex-direction: column;
}
textarea {
height: 30vh;
border-radius: 18px;
padding-left: 15px;
padding-top: 10px;
border: 2px solid #d7d7d7;
overflow: hidden;
overflow-y: scroll;
outline: none;
resize: none
}
input,
textarea {
font-family: "HelveticaNeueCyr";
font-weight: 100;
font-size: 18px;
}
::-webkit-input-placeholder {
color: gray;
font-size: 18px;
}
::-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 19+ */
:-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 18- */
:-ms-input-placeholder {
color: gray;
font-size: 18px;
}
input:not([type="submit"]) {
border-radius: 100px;
padding-left: 15px;
height: 36px;
border: none;
background: #f3f3f3;
}
input:focus {
outline: none;
border: 2px solid #f3f3f3;
box-sizing: border-box;
background: white;
padding-left: 13px;
}
.required {
display: inline-flex;
width: 100%;
flex-direction: column;
margin-bottom: 15px;
position: relative;
}
.iconrequired {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
width: 90px;
height: 14px;
color: white;
border-radius: 100px;
font-size: 10px;
font-weight: 100;
font-family: "HelveticaNeueCyr";
background: #343434;
position: absolute;
right: 15px;
top: 10px;
opacity: 1;
transition: opacity ease-out 1s;
animation: .05s ease-in-out 0s 4 alternate req;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
border: 2px solid #f3f3f3;
box-sizing: border-box;
padding-left: 13px;
}
div.button-set {
display: inline-flex;
}
div.button-set>label {
position: relative;
flex: 0 0 auto;
height: 50px;
width: 50px;
margin-left: 15px;
border-radius: 100px;
outline: none;
border: none;
margin-bottom: 20px;
}
.checked {
background: #f3f3f3;
border-radius: 100px;
}
input[type="submit"] {
font-family: "HelveticaNeueCyr";
height: 36px;
width: 160px;
font-weight: 100;
font-size: 24px;
margin-top: 20px;
margin-left: 10px;
border: none;
border-radius: 100px;
background: #f3f3f3;
padding: 0;
}
::-webkit-scrollbar {
position: absolute;
z-index: 9999;
width: 5px;
}
::-webkit-scrollbar-button {
display: none;
}
::-webkit-scrollbar-track {
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-track-piece {
z-index: 9999;
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-thumb {
z-index: 9999;
background-color: #d7d7d7;
border-radius: 3px;
}
::-webkit-scrollbar-corner {
z-index: 9999;
background-color: #d7d7d7;
}
.invalid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: tomato;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.valid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: #9dc46b;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.error {
text-align: right;
font-size: 12px;
padding-right: 20px;
padding-top: 10px;
color: gray;
letter-spacing: .05em;
}
.hide {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/form.css">
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form novalidate action="" method="post" name="support" id="support">
<label class="required"><span id="vs" class="invalid hide"></span><input id="sellection" class="mail sellection" name="sel" vlaue="" placeholder="choose a communication way...." required disabled><span id="error1"></span><div id="sellectionreq" class="iconrequired hide">REQUIRED</div></label>
<div class="button-set">
<label title="Email"><img class="icons" src='/img/icon/social_icon_mail_white.svg'><input class="radio" id="radio" type="radio" name="button-set" value="to mail" style="display:none;"></label>
<label for="radio1" title="WhatsApp"><img class="icons" src='/img/icon/social_icon_whatsapp_white.svg'><input class="radio" id="radio1" type="radio" name="button-set" value="to WhatsApp" style="display:none;"></label>
<label for="radio2" title="Telegram"><img class="icons" src='/img/icon/social_icon_telegram_white.svg'><input class="radio" id="radio2" type="radio" name="button-set" value="to Telegram" style="display:none;"></label>
<label for="radio3" title="Viber"><img class="icons" src='/img/icon/social_icon_viber_white.svg'><input class="radio" id="radio3" type="radio" name="button-set" value="to Viber" style="display:none;"></label>
</div>
<label class="required"><span id="vn" class="invalid hide"></span>
<input id="name" class="mail" type="name" name="name" autocomplete= none placeholder="what's your name...." value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="15" minlength="2" required><div id="namereq" class="iconrequired hide">REQUIRED</div></label>
<label class="required"><span id="vt" class="invalid hide"></span><textarea id="qestions" type="text" placeholder="your question...." name="message" value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="400" minlength="4" required></textarea><div id="textreq" class="iconrequired hide">REQUIRED</div></label>
<input name="submit" type="submit" id="submit" value="SUBMIT" />
</form>
<div id="message"></div>
</body>
<script src="/js/form.js"></script>
</html>
without counter:
var_dump($email,$change,$name,$question,$submit) - string(12)
"+79102054615" string(11) "to WhatsApp" string(4) "ZERG" string(8)
"ANYTHING" NULL
with counter:
var_dump($email,$change,$name,$question,$submit,$count) - string(12)
"+79102054615" string(11) "to WhatsApp" string(4) "ZERG" string(8)
"ANYTHING" NULL string(1) "9"
$count immediately takes on value "9"
site with form: https://www.archsupport.ru/

In regards to the HTML/JavaScript, consider the following code.
$(function() {
var form = $("#support");
function checkFieldValidity(fObj) {
var r = false;
var re = new RegExp(fObj.attr("pattern"));
var v = fObj.val();
if (fObj.is("[required]")) {
if (v.length) {
fObj.next(".iconrequired").hide();
} else {
fObj.next(".iconrequired").show();
}
if (re.test(v)) {
fObj.prev(".icon").removeClass("invalid").addClass("valid");
r = true;
} else {
fObj.prev(".icon").removeClass("valid").addClass("invalid");
}
} else {
r = true;
}
return r;
}
$("input", form).blur(function() {
checkFieldValidity($(this));
});
form.submit(function(e) {
e.preventDefault();
var valid = true;
$("[required]", form).each(function(i, el) {
valid = valid && checkFieldValidity($(el));
});
return valid;
});
$(".button-set label", form).on('click', function() {
$(this).parent().find(".checked").removeClass("checked");
$("img", this).addClass("checked");
var input = $("#sellection");
input.prop("disabled", false);
switch ($(this).data("value")) {
case "email":
input.prop({
type: "email",
placeholder: "example#yourmail.com",
autocomplete: "email",
maxlength: 35,
minlength: 12,
value: "",
}).attr("pattern", "^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$");
break;
// Add Cases for each selection option if needed
default:
input.prop({
"type": "tel",
"placeholder": "+7-910-205-46-15",
"autocomplete": "tel",
"maxlength": "16",
"minlength": "11",
"value": "",
});
input.attr("pattern", "\\+7\\s?[\\(]{0,1}9[0-9]{2}[\\)]{0,1}\\s?\\d{3}[-]{0,1}\\d{2}[-]{0,1}\\d{2}");
break;
}
input.focus();
input.val("");
});
});
#keyframes req {
0% {
transform: translatex(0px);
}
100% {
transform: translatex(5px);
}
}
#keyframes inv {
0% {
opacity: .5;
}
100% {
opacity: 1;
}
}
* {
padding: 0;
margin: 0;
}
:root {
font-family: "HelveticaNeueCyr";
font-weight: 100;
}
form {
font-size: 24px;
position: relative;
width: 100%;
display: inline-flex;
flex-direction: column;
}
textarea {
height: 30vh;
border-radius: 18px;
padding-left: 15px;
padding-top: 10px;
border: 2px solid #d7d7d7;
overflow: hidden;
overflow-y: scroll;
outline: none;
resize: none
}
input,
textarea {
font-family: "HelveticaNeueCyr";
font-weight: 100;
font-size: 18px;
}
::-webkit-input-placeholder {
color: gray;
font-size: 18px;
}
::-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 19+ */
:-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 18- */
:-ms-input-placeholder {
color: gray;
font-size: 18px;
}
input:not([type="submit"]) {
border-radius: 100px;
padding-left: 15px;
height: 36px;
border: none;
background: #f3f3f3;
}
input:focus {
outline: none;
border: 2px solid #f3f3f3;
box-sizing: border-box;
background: white;
padding-left: 13px;
}
.required {
display: inline-flex;
width: 100%;
flex-direction: column;
margin-bottom: 15px;
position: relative;
}
.iconrequired {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
width: 90px;
height: 14px;
color: white;
border-radius: 100px;
font-size: 10px;
font-weight: 100;
font-family: "HelveticaNeueCyr";
background: #343434;
position: absolute;
right: 15px;
top: 10px;
opacity: 1;
transition: opacity ease-out 1s;
animation: .05s ease-in-out 0s 4 alternate req;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
border: 2px solid #f3f3f3;
box-sizing: border-box;
padding-left: 13px;
}
div.button-set {
display: inline-flex;
}
div.button-set>label {
position: relative;
flex: 0 0 auto;
height: 50px;
width: 50px;
margin-left: 15px;
border-radius: 100px;
outline: none;
border: none;
margin-bottom: 20px;
}
.checked {
background: #f3f3f3;
border-radius: 100px;
}
input[type="submit"] {
font-family: "HelveticaNeueCyr";
height: 36px;
width: 160px;
font-weight: 100;
font-size: 24px;
margin-top: 20px;
margin-left: 10px;
border: none;
border-radius: 100px;
background: #f3f3f3;
padding: 0;
}
::-webkit-scrollbar {
position: absolute;
z-index: 9999;
width: 5px;
}
::-webkit-scrollbar-button {
display: none;
}
::-webkit-scrollbar-track {
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-track-piece {
z-index: 9999;
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-thumb {
z-index: 9999;
background-color: #d7d7d7;
border-radius: 3px;
}
::-webkit-scrollbar-corner {
z-index: 9999;
background-color: #d7d7d7;
}
.invalid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: tomato;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.valid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: #9dc46b;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.error {
text-align: right;
font-size: 12px;
padding-right: 20px;
padding-top: 10px;
color: gray;
letter-spacing: .05em;
}
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form novalidate action="" method="post" name="support" id="support">
<span class="icon"></span><input id="sellection" class="mail" name="f[sel]" value="" placeholder="Choose a communication method...." required disabled>
<div class="iconrequired hide">REQUIRED</div>
<div class="button-set">
<label title="Email" data-value="email"><img class="icon" src='/img/icon/social_icon_mail_white.svg'></label>
<label title="WhatsApp" data-value="whatsapp"><img class="icon" src='/img/icon/social_icon_whatsapp_white.svg'></label>
<label title="Telegram" data-value="telegram"><img class="icon" src='/img/icon/social_icon_telegram_white.svg'></label>
<label title="Viber" data-value="viber"><img class="icon" src='/img/icon/social_icon_viber_white.svg'></label>
</div>
<label class="required"><span class="icon"></span>
<input id="name" class="mail" type="name" name="f[name]" autocomplete="none" placeholder="what's your name...." value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="15" minlength="2" required><div id="namereq" class="iconrequired hide">REQUIRED</div></label>
<label class="required"><span id="vt" class="invalid hide"></span><textarea id="qestions" type="text" placeholder="your question...." name="f[message]" value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="400" minlength="45" required></textarea><div id="textreq" class="iconrequired hide">REQUIRED</div></label>
<input name="f[submit]" type="submit" id="submit" value="SUBMIT" />
</form>
<div id="message"></div>
You want to evaluate if each field that is required has content and matches a specific pattern. I think your approach was too complicated. Additionally, I would stick with all native JavaScript or all jQuery. Don't mix them.
For submit, you will want to test each field and keep a running tally. To do this, you can logically start with a true value and as you test, keep logically evaluating. Example:
var result = true;
result = result && true; // result is true
result = result && false; // result is false
result = result && true; // result is false
If some of the fields validate and if any do not, the result will be false and the form should not submit. If all validate, the result will be true and it's safe to submit the data to PHP. This should also prevent multiple submissions.
Remember that this is Client Side validation and can be bypassed by posting the data manually to the PHP. Most users will not even bother, yet all it takes is one curious or malicious User or Bot to see that they can bypass the form and create their own HTTP Post Payload. So you will want to ensure that your PHP is protected from such actions. Test any data submitted by the User before using it in your PHP Code. For example, you define $name like so:
$name = ($_POST['name']);
If I construct a payload like:
&name=;include "/etc/passwd";
This might get evaluated in the following code:
$message = 'Name: ' . $name . "\r\n" . 'Contacts: ' . $email . "\r\n" . 'Write ' . $change . "\r\n" . 'Question: ' . $question;
Just some things to consider.

Related

How would I toggle an object property between true and false?

let myLibrary = [
{
id: 0,
title: "The Once and Future King",
author: "White",
pages: 654,
read: false,
},
{
id: 1,
title: "The Hobbit",
author: "Tolkien",
pages: 304,
read: false,
},
];
const bookContent = document.getElementById("content");
function displayBook(book) {
const addBook = document.createElement("div");
addBook.className = "book";
addBook.id = book.id;
bookContent.appendChild(addBook);
addBook.innerHTML = `
<div class="title">
<p class="bookTitle">
<span>${book.title}</span>
</p>
</div>
<div class="body">
<p>
Author: <span>${book.author}</span>
</p>
<p>
Pages: <span>${book.pages}</span>
</p>
</div>
<div class="read">
<label class="switch" data-book="0">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
<div class="delete">
<button class="delete-btn">DELETE</button>
</div>`;
}
// Display your original object list
myLibrary.forEach((book) => {
displayBook(book);
});
// Handle your object creation
const form = document.getElementById("form");
form.addEventListener("submit", updateLibrary);
function updateLibrary(event) {
// Need this so it doesn't refresh page
event.preventDefault();
const title = document.getElementById("title").value;
const author = document.getElementById("author").value;
const pages = document.getElementById("pages").value;
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
// Adds object to array
myLibrary.push(book);
// Displays new book
displayBook(book);
// Reset form
resetForm();
// Close form
document.getElementById("addBookForm").style.display = "none";
console.log(myLibrary);
}
// Resets the form so user can input another book
function resetForm() {
document.getElementById("form").reset();
}
// The form is automatically set to hidden. This loads it up for the user
const openForm = function () {
document.getElementById("addBookForm").style.display = "block";
document.getElementById("title").focus();
};
// Sets the form display back to none
const closeForm = () =>
(document.getElementById("addBookForm").style.display = "none");
/* .main {
} */
.header {
display: flex;
flex-direction: column;
background-color: #c689c6;
height: 150px;
border: 1px solid #3b133b;
}
.btn {
margin: 0 auto;
margin-top: 55px;
display: block;
text-align: center;
background-color: #4649ff;
padding: 0.75rem 1.25rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
font-size: 1rem;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.btn:hover {
background-color: #3134fa;
}
.content {
display: flex;
flex-flow: row wrap;
align-content: flex-start;
justify-content: flex-start;
background-color: #fffdfa;
height: auto;
}
.book {
border: 2px solid #ffa94d;
background-color: #ffd8a8;
color: #d9480f;
width: 280px;
height: 365px;
margin: 10px;
}
.title {
border-bottom: 2px solid #ffa94d;
}
.title p {
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: larger;
}
.title span {
color: #3c4048;
}
.body {
border: 1px solid transparent;
height: 200px;
background-color: #fff4e6;
}
.body p {
padding-left: 20px;
}
p span {
color: #3c4048;
}
.read {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
border-top: 2px solid #ffa94d;
text-align: center;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked + .slider {
background-color: #3d8361;
}
input:focus + .slider {
box-shadow: 0 0 1px #3d8361;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.delete {
height: 50px;
border-top: 2px solid #ffa94d;
}
.delete-btn {
margin: 0 auto;
margin-top: 8px;
display: block;
text-align: center;
background-color: #e94560;
padding: 0.5rem 0.75rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.delete-btn:hover {
background-color: #e7082d;
}
.close-btn {
color: #e7082d;
font-size: large;
background-color: #c689c6;
border: none;
float: right;
cursor: pointer;
}
/* THE FORM */
.form-content {
display: flex;
justify-content: center;
}
.form {
display: none;
position: fixed;
margin-top: 5px;
border: 2px solid #3b133b;
animation: openForm 0.5s;
z-index: 1;
}
#keyframes openForm {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
.form h1 {
text-align: center;
}
.form-container {
background-color: #c689c6;
border: 2px solid black;
max-width: 300px;
padding: 10px;
}
.form-container h1 {
padding-left: 20px;
}
.form-container input[type="text"],
.form-container input[type="number"] {
width: 80%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
}
.form-container input[type="text"]:focus,
.form-container input[type="number"]:focus {
outline: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<title>Library</title>
</head>
<body>
<div class="main">
<div class="header">
<button class="btn" id="btn" onclick="openForm()">Add a Book</button>
</div>
<div class="form-content">
<div class="form" id="addBookForm">
<form id="form" action="" class="form-container">
<button type="button" class="close-btn" onclick="closeForm()">
x
</button>
<h1>Add a Book</h1>
<label for="title">Title</label>
<input
type="text"
placeholder="Title"
name="title"
id="title"
required
/>
<label for="author">Author</label>
<input
type="text"
placeholder="Author"
name="author"
id="author"
required
/>
<label for="pages">Pages</label>
<input
type="number"
placeholder="Pages"
name="pages"
required
id="pages"
/>
<button type="submit" id="submit-btn">Submit</button>
</form>
</div>
</div>
<div id="content" class="content"></div>
</div>
</body>
</html>
I have a form where the user inputs information from a book they are reading and upon hitting submit, the information is sent as its own object inside an array. I also have a forEach method running which loops through the array and displays each object as a div on the web page.
let myLibrary = [];
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
myLibrary.push(book)
As you can see from the code above, the three properties that the user fills out are the books title, author and page count. There's also a property that is automatically added called the read property and it is automatically set as false.
The Problem
My problem is this. I have the following code displayed at the bottom of each div.
<div class="read">
<label class="switch">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
This code is very simple. It's a toggle switch which I found here.
I want it so when the toggle switch is grayed out, the read status is set to false. But when the toggle switch is turned on, the read property is set to true. I am having a very difficult time figuring out how to get this done.
What I've Tried
I was able to use an onclick to select the toggle switch's parent element, and I tested it using console.log however I am unsure of where to go from there. I attempted to update the book.read to true using the ternary operator but it was out of scope and resulted in an error.
document.querySelector(".main").onclick = (ev) => {
let el = ev.target.classList.contains("switch")
? ev.target.parentElement
: ev.target.classList.contains("slider")
? ev.target
: false;
if (el) {
let toggle = el.parentElement.parentElement.parentElement;
let index = [...toggle.parentElement.children].indexOf(toggle);
myLibrary[index].read = false ? false : true;
console.log(myLibrary[index].read);
}
console.log(myLibrary);
};
Change this
function displayBook(book) {
...
<label class="switch" data-book="0">
to
function displayBook(book,bookIndex) {
...
<label class="switch" data-book="${bookIndex}">
and
myLibrary.forEach((book) => {
displayBook(book);
});
to
myLibrary.forEach((book,i) => {
displayBook(book,i);
});
lastly change
// Displays new book
displayBook(book);
to
// Displays new book
displayBook(book,myLibrary.length-1);
Here is the code inclusive a delete function
It would be slightly simpler if we had an associate array on book_id
Note I removed the numeric ID because it is not needed since the index of the array is the same
let myLibrary = [{
title: "The Once and Future King",
author: "White",
pages: 654,
read: false,
},
{
title: "The Hobbit",
author: "Tolkien",
pages: 304,
read: false,
},
];
const bookContent = document.getElementById("content");
const formDiv = document.getElementById("addBookForm");
function displayBook(book, idx) {
const addBook = document.createElement("div");
addBook.className = "book";
addBook.id = `book_${idx}`;
bookContent.appendChild(addBook);
addBook.innerHTML = `
<div class="title">
<p class="bookTitle">
<span>${book.title}</span>
</p>
</div>
<div class="body">
<p>
Author: <span>${book.author}</span>
</p>
<p>
Pages: <span>${book.pages}</span>
</p>
</div>
<div class="read">
<label class="switch" data-book="${idx}">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
<div class="delete">
<button class="delete-btn">DELETE</button>
</div>`;
}
// Display your original object list
myLibrary.forEach((book, i) => {
displayBook(book, i);
});
const deleteBook = (e) => {
const parent = e.target.closest("div.book");
const idx = parent.querySelector(".switch").dataset.book;
parent.remove();
console.log(idx);
myLibrary.splice(idx, 1);
console.log(myLibrary);
content.querySelectorAll("div.book").forEach((book, i) => { // reset the hard way
book.id = `book_${i}`;
book.querySelector("label.switch").dataset.book = i;
})
};
content.addEventListener("click", function(e) {
const tgt = e.target;
if (!tgt.matches(".delete-btn")) return; // not the delete
deleteBook(e); // pass the event to the delete
})
// Handle your object creation
const form = document.getElementById("form");
form.addEventListener("submit", updateLibrary);
function updateLibrary(event) {
// Need this so it doesn't refresh page
event.preventDefault();
const title = document.getElementById("title").value;
const author = document.getElementById("author").value;
const pages = document.getElementById("pages").value;
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
// Adds object to array
myLibrary.push(book);
// Displays new book
displayBook(book);
// Reset form
resetForm();
// Close form
formDiv.style.display = "none";
console.log(myLibrary);
}
// Resets the form so user can input another book
function resetForm() {
document.getElementById("form").reset();
}
// The form is automatically set to hidden. This loads it up for the user
const openForm = function() {
formDiv.style.display = "block";
document.getElementById("title").focus();
};
// Sets the form display back to none
const closeForm = () => formDiv.style.display = "none";
/* .main {
} */
.header {
display: flex;
flex-direction: column;
background-color: #c689c6;
height: 150px;
border: 1px solid #3b133b;
}
.btn {
margin: 0 auto;
margin-top: 55px;
display: block;
text-align: center;
background-color: #4649ff;
padding: 0.75rem 1.25rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
font-size: 1rem;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.btn:hover {
background-color: #3134fa;
}
.content {
display: flex;
flex-flow: row wrap;
align-content: flex-start;
justify-content: flex-start;
background-color: #fffdfa;
height: auto;
}
.book {
border: 2px solid #ffa94d;
background-color: #ffd8a8;
color: #d9480f;
width: 280px;
height: 365px;
margin: 10px;
}
.title {
border-bottom: 2px solid #ffa94d;
}
.title p {
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: larger;
}
.title span {
color: #3c4048;
}
.body {
border: 1px solid transparent;
height: 200px;
background-color: #fff4e6;
}
.body p {
padding-left: 20px;
}
p span {
color: #3c4048;
}
.read {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
border-top: 2px solid #ffa94d;
text-align: center;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked+.slider {
background-color: #3d8361;
}
input:focus+.slider {
box-shadow: 0 0 1px #3d8361;
}
input:checked+.slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.delete {
height: 50px;
border-top: 2px solid #ffa94d;
}
.delete-btn {
margin: 0 auto;
margin-top: 8px;
display: block;
text-align: center;
background-color: #e94560;
padding: 0.5rem 0.75rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.delete-btn:hover {
background-color: #e7082d;
}
.close-btn {
color: #e7082d;
font-size: large;
background-color: #c689c6;
border: none;
float: right;
cursor: pointer;
}
/* THE FORM */
.form-content {
display: flex;
justify-content: center;
}
.form {
display: none;
position: fixed;
margin-top: 5px;
border: 2px solid #3b133b;
animation: openForm 0.5s;
z-index: 1;
}
#keyframes openForm {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
.form h1 {
text-align: center;
}
.form-container {
background-color: #c689c6;
border: 2px solid black;
max-width: 300px;
padding: 10px;
}
.form-container h1 {
padding-left: 20px;
}
.form-container input[type="text"],
.form-container input[type="number"] {
width: 80%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
}
.form-container input[type="text"]:focus,
.form-container input[type="number"]:focus {
outline: none;
}
<div class="main">
<div class="header">
<button class="btn" id="btn" onclick="openForm()">Add a Book</button>
</div>
<div class="form-content">
<div class="form" id="addBookForm">
<form id="form" action="" class="form-container">
<button type="button" class="close-btn" onclick="closeForm()">
x
</button>
<h1>Add a Book</h1>
<label for="title">Title</label>
<input type="text" placeholder="Title" name="title" id="title" required />
<label for="author">Author</label>
<input type="text" placeholder="Author" name="author" id="author" required />
<label for="pages">Pages</label>
<input type="number" placeholder="Pages" name="pages" required id="pages" />
<button type="submit" id="submit-btn">Submit</button>
</form>
</div>
</div>
<div id="content" class="content"></div>
</div>

Html contact form button is inactive

I have used an html contact form template found online for my static website hosted on aws.
The html contact form in its head section is linked to a js script with a formula, provided together with the html template.
Behind that on aws I have created a lambda formula to fetch the massages via api gateway and use ses to forward them to an email address, that part should be ok.
Unfortunately it does not seem to work and I think it's something related to the html part as the button seems inactive.
Here below the html script (just hid the datasite key):
function submitToAPI(e) {
e.preventDefault();
var URL = "https://XXXX.execute-api.us-east-1.amazonaws.com/001/contact-us";
var Namere = /[A-Za-z]{1}[A-Za-z]/;
if (!Namere.test($("#name-input").val())) {
alert("Name can not less than 2 char");
return;
}
var mobilere = /[0-9]{10}/;
if (!mobilere.test($("#phone-input").val())) {
alert("Please enter valid mobile number");
return;
}
if ($("#email-input").val() == "") {
alert("Please enter your email id");
return;
}
var reeamil = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
if (!reeamil.test($("#email-input").val())) {
alert("Please enter valid email address");
return;
}
var name = $("#name-input").val();
var phone = $("#phone-input").val();
var email = $("#email-input").val();
var desc = $("#description-input").val();
var data = {
name: name,
phone: phone,
email: email,
desc: desc
};
$.ajax({
type: "POST",
url: "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function() {
// clear form and show a success message
alert("Successfull");
document.getElementById("contact-form").reset();
location.reload();
},
error: function() {
// show an error message
alert("UnSuccessfull");
}
});
}
#fcf-form {
display:block;
}
.fcf-body {
margin: 0;
font-family: -apple-system, Arial, sans-serif;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #212529;
text-align: left;
background-color: #fff;
padding: 30px;
padding-bottom: 10px;
border: 1px solid #ced4da;
border-radius: 0.25rem;
max-width: 50%;
}
.fcf-form-group {
margin-bottom: 1rem;
}
.fcf-input-group {
position: relative;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-ms-flex-align: stretch;
align-items: stretch;
width: 100%;
}
.fcf-form-control {
display: block;
width: 100%;
height: calc(1.5em + 0.75rem + 2px);
padding: 0.375rem 0.75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
outline: none;
border-radius: 0.25rem;
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
.fcf-form-control:focus {
border: 1px solid #313131;
}
select.fcf-form-control[size], select.fcf-form-control[multiple] {
height: auto;
}
textarea.fcf-form-control {
font-family: -apple-system, Arial, sans-serif;
height: auto;
}
label.fcf-label {
display: inline-block;
margin-bottom: 0.5rem;
}
.fcf-credit {
padding-top: 10px;
font-size: 0.9rem;
color: #545b62;
}
.fcf-credit a {
color: #545b62;
text-decoration: underline;
}
.fcf-credit a:hover {
color: #0056b3;
text-decoration: underline;
}
.fcf-btn {
display: inline-block;
font-weight: 400;
color: #212529;
text-align: center;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-color: transparent;
border: 1px solid transparent;
padding: 0.375rem 0.75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: 0.25rem;
transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
#media (prefers-reduced-motion: reduce) {
.fcf-btn {
transition: none;
}
}
.fcf-btn:hover {
color: #212529;
text-decoration: none;
}
.fcf-btn:focus, .fcf-btn.focus {
outline: 0;
box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}
.fcf-btn-primary {
color: #fff;
background-color: #007bff;
border-color: #007bff;
}
.fcf-btn-primary:hover {
color: #fff;
background-color: #0069d9;
border-color: #0062cc;
}
.fcf-btn-primary:focus, .fcf-btn-primary.focus {
color: #fff;
background-color: #0069d9;
border-color: #0062cc;
box-shadow: 0 0 0 0.2rem rgba(38, 143, 255, 0.5);
}
.fcf-btn-lg, .fcf-btn-group-lg>.fcf-btn {
padding: 0.5rem 1rem;
font-size: 1.25rem;
line-height: 1.5;
border-radius: 0.3rem;
}
.fcf-btn-block {
display: block;
width: 100%;
}
.fcf-btn-block+.fcf-btn-block {
margin-top: 0.5rem;
}
input[type="submit"].fcf-btn-block, input[type="reset"].fcf-btn-block, input[type="button"].fcf-btn-block {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<center>
<link href="contact-form.css" rel="stylesheet">
<div class="fcf-body">
<head>
<script type="text/javascript" src="form-control.js"></script>
</head>
<form id="contact-form" method="post">
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Phone:</h4>
<input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;" /><br/>
<h4>Email:</h4>
<input type="email" style="height:35px;" id="email-input" placeholder="Enter email here…" class="form-control" style="width:100%;" /><br/>
<h4>How can we help you?</h4>
<textarea id="description-input" rows="3" placeholder="Enter your message…" class="form-control" style="width:100%;"></textarea><br/>
<div class="g-recaptcha" data-sitekey="XXX" class="form-control" style="width:100%;"></div>
<button type="button" onClick="submitToAPI(event)" class="btn btn-lg" style="margin-top:20px;">Submit</button>
</form>
</div>
</center>
Can anyone let me know what am I missing/doing wrong so that the contact form works?
Thank you

Form validation by pure JS

I am a stuck on following issues:
How to add required error just once after first click on submit button? And not at any subsequent click after.
How can to start function (checkValid()) with RegExp validation only after first function (checkRequired()) implementation with required checking?
How to show every error after RegExp validation in its relative element? Now all errors are displayed in the last block with phone input.
Here is case on jsfiddle:
https://jsfiddle.net/SanchezMalina/hno7v4tf/35/
Or code here:
// regexp pattern functions
function validateEmail(email) {
let re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email.toLowerCase());
}
function validatePhone(phone) {
let re = /^[0-9]{7,20}$/;
return re.test(phone.toLowerCase());
}
function validateName(name) {
let re = /^([a-zA-Z0-9А]){3,50}$/;
return re.test(name.toLowerCase());
}
let flag = false;
// check required fields
function checkRequired() {
let notFilled = document.querySelectorAll('.is-required');
notFilled.forEach(function (el) {
if (el.value === '') {
el.parentElement.classList.add('is-empty');
addRequiredError();
} else {
el.parentElement.classList.remove('is-empty');
removeRequiredError();
}
});
}
let formFields = document.querySelectorAll('.form__field');
//add required error message
function addRequiredError() {
let errorRequiredMsg = document.createElement('div');
errorRequiredMsg.classList.add('input-required');
errorRequiredMsg.innerHTML = `<span> This field is required! </span>`;
formFields.forEach( function (elem) {
if (elem.classList.contains('is-empty')) {
elem.appendChild(errorRequiredMsg);
}
});
}
//remove required error message
function removeRequiredError() {
let requiredErrorMsg = document.querySelectorAll('.form__field .input-required');
requiredErrorMsg.forEach(function (elem) {
elem.parentElement.removeChild(elem);
});
flag = true;
}
//check validation inputs
function checkValid() {
let firstName = document.querySelector('#f-name');
let lastName = document.querySelector('#l-name');
let selectCountry = document.querySelector('.form__select');
let phone = document.querySelector('#cell');
let email = document.querySelector('#email');
formFields.forEach(function () {
if(!validateName(firstName.value) && !validateName(lastName.value) && !validatePhone(phone.value) && !validateEmail(email.value)) {
firstName.parentElement.classList.add('is-error');
lastName.parentElement.classList.add('is-error');
selectCountry.parentElement.classList.add('is-error');
phone.parentElement.classList.add('is-error');
email.parentElement.classList.add('is-error');
addValidError();
} else {
firstName.parentElement.classList.remove('is-error');
lastName.parentElement.classList.remove('is-error');
selectCountry.parentElement.classList.remove('is-error');
phone.parentElement.classList.remove('is-error');
email.parentElement.classList.remove('is-error');
removeValidError();
}
});
}
//add invalid error message
function addValidError() {
let errorValidMsg = document.createElement('div');
errorValidMsg.classList.add('input-error');
errorValidMsg.innerHTML = `<span> Input is invalid! </span>`;
formFields.forEach(function (elem) {
if (elem.classList.contains('is-error')) {
elem.appendChild(errorValidMsg);
}
});
// for (let i = 0; i < formFields.length; i++) {
//
// if (formFields[i].classList.contains('is-error')) {
//
// formFields[i].appendChild(errorValidMsg);
//
// }
// }
}
//remove invalid error message
function removeValidError() {
let requiredErrorMsg = document.querySelectorAll('.input-error');
requiredErrorMsg.forEach(function (elem) {
elem.parentNode.removeChild(elem);
})
}
//form submit handler
let formTrial = document.querySelector('.form__main');
formTrial.addEventListener('submit', function (event) {
event.preventDefault();
checkRequired();
console.log(flag);
if(flag !== false) {
checkValid();
}
});
.form__main {
display: block;
margin: 25px auto;
width: 450px;
}
.form__field {
position: relative;
margin: 10px 0;
padding: 5px 15px;
background-color: #fff;
height: 50px;
}
.form__field_select::after {
content: "";
width: 0;
height: 0;
border: 7px solid transparent;
border-color: #000 transparent transparent transparent;
position: absolute;
top: 55%;
right: 17px;
transform: translateY(-50%);
}
.form__input {
position: absolute;
left: 0;
top: 10px;
right: 0;
bottom: 10px;
padding-left: 45px;
background: none;
font-size: 14px;
font-weight: 400;
font-family: "Open Sans", sans-serif;
width: 100%;
color: #333;
line-height: 1.714;
box-sizing: border-box;
}
.form__input:focus ~ .form__label,
.form__input:valid ~ .form__label {
top: 0;
left: 45px;
transform: scale(0.6, 0.6);
color: #000;
}
.form__input:focus ~ .form__label[for=cell],
.form__input:valid ~ .form__label[for=cell] {
top: 0;
left: 125px;
}
.form__input[type=tel] {
padding-left: 125px;
}
.form__input:-webkit-autofill {
-webkit-box-shadow: 0 0 0 100px white inset;
}
.form__label {
position: absolute;
top: 50%;
left: 50px;
transform-origin: left top;
transition: all 0.3s ease;
transform: translateY(-50%);
font-size: 14px;
font-family: "Open Sans", sans-serif;
color: #999999;
line-height: 1.714;
}
.form__label[for=cell] {
left: 135px;
}
.form__select {
position: absolute;
width: 100%;
height: 100%;
top: 50%;
transform: translateY(-50%);
left: 0;
right: 0;
padding-left: 50px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-appearance: none;
-moz-appearance: none;
background-color: transparent;
border-color: #fff;
font-size: 14px;
font-family: "Open Sans", sans-serif;
color: #000;
line-height: 1.714;
}
.form__country-code {
position: absolute;
color: #000;
left: 50px;
font-size: 14px;
font-family: "Open Sans", sans-serif;
line-height: 2;
height: 100%;
top: 0;
bottom: 0;
display: flex;
align-items: center;
border-right: 1px solid;
padding-right: 20px;
z-index: 2;
}
.form .btn {
width: 100%;
margin: 20px 0;
}
.form .btn:hover {
transform: translateY(-5px);
box-shadow: 1px 3px 20px #c5f833;
}
<form method="post" class="form__main" novalidate>
<div class="form__field">
<i class="icon icon-user"></i>
<input class="form__input is-required" id="f-name" type="text" required>
<label class="form__label" for="f-name">First Name</label>
</div>
<div class="form__field">
<i class="icon icon-user"></i>
<input class="form__input is-required" id="l-name" type="text" required>
<label class="form__label" for="l-name">Last Name</label>
</div>
<div class="form__field">
<i class="icon icon-envelop"></i>
<input class="form__input" id="email" type="text" required>
<label class="form__label" for="email">Email</label>
</div>
<div class="form__field form__field_select">
<i class="icon icon-pin"></i>
<select class="form__select" name="country">
<option value="ro" selected>USA</option>
<option value="ua">India</option>
<option value="il">Spain</option>
</select>
</div>
<div class="form__field">
<i class="icon icon-phone"></i>
<span class="form__country-code">+10000</span>
<input class="form__input" id="cell" type="tel" required>
<label class="form__label" for="cell">Phone</label>
</div>
<button class="btn btn_lime">Try for free</button>
</form>
1)
if( !el.parentElement.classList.contains('is-empty') ) {
addRequiredError();
}
2)
not sure to understand the question
3)
function addValidError() {
let errorValidMsg = document.createElement('div');
errorValidMsg.classList.add('input-error');
errorValidMsg.innerHTML = '<span> Input is invalid! </span>';
formFields.forEach(function (elem) { // <-- here formFields is not defined
}

Validation and button problem before next page

I am creating a multi form.
When I do not input any words and click the next button, the system has a display function validation but it also goes to next page automaticly.
So, what I need todo, is detect when I input a wrong format or empty string, so the system will make a validation and not automaticly go to the next page.
Finally, how can I click the submit button have the system save all my form data?
Here's is my script:
function page1() {
var name = document.forms["form1"]["name"].value
var email = document.forms["form1"]["email"].value
if (name == "" || !isNaN(name)) {
alert("Please enter correct name");
return false;
}
if (email.match(/^[\w\d._-]+#[\w\d.-]+\.[\w\d]{2,6}$/)) {
} else {
alert("Please enter correct email");
return false;
}
}
function page2() {
var phone = document.forms["form1"]["phone"].value
var address = document.forms["form1"]["address"].value
if (address == "" || !isNaN(address)) {
alert("Please enter correct address");
return false;
}
if (phone == "" || phone.length <= 9 || phone.length > 13 || isNaN(phone)) {
alert("Please enter correct phone");
return false;
}
return true;
}
function page3() {
var password = document.forms["form1"]["password"].value
var password2 = document.forms["form1"]["password"].value
if (password.match(/((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{8,15})/)) {
} else {
alert("Please enter correct password");
return false;
}
if (password1 != password2) {
alert("Password and Re-enter Password was not same");
return false;
}
return true;
}
$(document).ready(function() {
$(".form-wrapper .button1").click(function() {
$(this).closest("form1").find("input[type=text], input[type=password]").val("");
var button = $(this);
var currentSection = button.parents(".section");
var currentSectionIndex = currentSection.index();
var headerSection = $('.steps li').eq(currentSectionIndex);
currentSection.removeClass("is-active").next().addClass("is-active");
headerSection.removeClass("is-active").next().addClass("is-active");
$(".form-wrapper").submit(function(e) {
e.preventDefault();
submit = $(this);
});
if (currentSectionIndex === 3) {
$(document).find(".form-wrapper .section").first().addClass("is-active");
$(document).find(".steps li").first().addClass("is-active");
}
});
});
$(document).ready(function() {
$(".form-wrapper .button2").click(function() {
var button = $(this);
var currentSection = button.parents(".section");
var currentSectionIndex = currentSection.index();
var headerSection = $('.steps li').eq(currentSectionIndex);
currentSection.removeClass("is-active").prev().addClass("is-active");
headerSection.removeClass("is-active").prev().addClass("is-active");
$(".form-wrapper").submit(function(e) {
e.preventDefault();
this.submit();
});
if (currentSectionIndex === 3) {
$(document).find(".form-wrapper .section").first().addClass("is-active");
$(document).find(".steps li").first().addClass("is-active");
}
});
});
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: 'Open Sans', sans-serif;
background-color: #fff;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: #fff;
font-weight: 200;
}
a {
text-decoration: none;
}
p,
li,
a {
font-size: 14px;
}
fieldset {
margin: 0;
padding: 0;
border: none;
color: #fff;
}
/* GRID */
.twelve {
width: 100%;
}
.eleven {
width: 91.53%;
}
.ten {
width: 83.06%;
}
.nine {
width: 74.6%;
}
.eight {
width: 66.13%;
}
.seven {
width: 57.66%;
}
.six {
width: 49.2%;
}
.five {
width: 40.73%;
}
.four {
width: 32.26%;
}
.three {
width: 23.8%;
}
.two {
width: 15.33%;
}
.one {
width: 6.866%;
}
/* COLUMNS */
.col {
display: block;
float: left;
margin: 0 0 0 1.6%;
}
.col:first-of-type {
margin-left: 0;
}
.container {
width: 100%;
max-width: 700px;
margin: 0 auto;
position: relative;
}
.row {
padding: 20px 0;
}
/* CLEARFIX */
.cf:before,
.cf:after {
content: " ";
display: table;
}
.cf:after {
clear: both;
}
.cf {
*zoom: 1;
}
.wrapper {
width: 100%;
margin: 30px 0;
}
/* STEPS */
.steps {
list-style-type: none;
margin: 0;
padding: 0;
background-color: #000;
text-align: center;
}
.steps li {
display: inline-block;
margin: 20px;
color: #ccc;
padding-bottom: 5px;
}
.steps li.is-active {
border-bottom: 1px solid #fff;
color: #fff;
}
/* FORM */
.form-wrapper .section {
padding: 0px 20px 30px 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
background-color: #000;
opacity: 0;
-webkit-transform: scale(1, 0);
-ms-transform: scale(1, 0);
-o-transform: scale(1, 0);
transform: scale(1, 0);
-webkit-transform-origin: top center;
-moz-transform-origin: top center;
-ms-transform-origin: top center;
-o-transform-origin: top center;
transform-origin: top center;
-webkit-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
text-align: center;
position: absolute;
width: 100%;
min-height: 300px
}
.form-wrapper .section h3 {
margin-bottom: 30px;
}
.form-wrapper .section.is-active {
opacity: 1;
-webkit-transform: scale(1, 1);
-ms-transform: scale(1, 1);
-o-transform: scale(1, 1);
transform: scale(1, 1);
}
.form-wrapper .button1,
.form-wrapper .submit {
background-color: #fff;
display: inline-block;
padding: 8px 30px;
color: #000;
cursor: pointer;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
position: absolute;
right: 20px;
bottom: 20px;
}
.form-wrapper .button2 {
background-color: #fff;
display: inline-block;
padding: 8px 30px;
color: #000;
cursor: pointer;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
position: absolute;
left: 20px;
bottom: 20px;
}
.form-wrapper .submit {
border: none;
outline: none;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.form-wrapper input[type="text"],
.form-wrapper input[type="password"] {
display: block;
padding: 10px;
margin: 10px auto;
background-color: #f1f1f1;
border: none;
width: 50%;
outline: none;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<div class="container">
<div class="wrapper">
<ul class="steps">
<li class="is-active">Step 1</li>
<li>Step 2</li>
<li>Step 3</li>
</ul>
<form class="form-wrapper" id="form1" onsumbit="return submit1()">
<fieldset class="section is-active">
<h3>Your Details</h3>
<input type="text" name="name" id="name" placeholder="Name">
<input type="text" name="email" id="email" placeholder="Email">
<input class="button1" type="button" value="Next" onclick="return page1()">
</fieldset>
<fieldset class="section">
<h3>other Details</h3>
<input type="text" name="phone" id="phone" placeholder="Phone">
<input type="text" name="address" id="address" placeholder="address">
<input class="button2" type="button" value="Previous">
<input class="button1" type="button" value="Next" onclick="return page2()">
</fieldset>
<fieldset class="section">
<h3>Choose a Password</h3>
<input type="password" name="password" id="password" placeholder="Password">
<input type="password" name="password2" id="password2" placeholder="Re-enter Password">
<input class="button2" type="button" value="Previous">
<input class="submit button1" type="submit" value="Sign Up" onclick="return page3()">
</fieldset>
<fieldset class="section">
<h3>Account Created!</h3>
<p>Your account has now been created.</p>
<div class="button1">Reset Form</div>
</fieldset>
</form>
</div>
</div>
You do not need onclick event on the button of the page1, page2, page3.
remove onclick="return page1()" call the functions
Just use one event onclick and it should work, add classes to check the validations, this is what I did.
if ($(this).hasClass('page1')) {
if (!page1()) {
return;
}
}
else if ($(this).hasClass('page2')) {
if (!page2()) {
return;
}
}
else if ($(this).hasClass('page3')) {
if (!page3()) {
return;
}
}
function page1() {
var name = document.forms["form1"]["name"].value
var email = document.forms["form1"]["email"].value
if (name == "" || !isNaN(name)) {
alert("Please enter correct name");
return false;
}
if (email.match(/^[\w\d._-]+#[\w\d.-]+\.[\w\d]{2,6}$/)) {
} else {
alert("Please enter correct email");
return false;
}
return true;
}
function page2() {
var phone = document.forms["form1"]["phone"].value
var address = document.forms["form1"]["address"].value
if (address == "" || !isNaN(address)) {
alert("Please enter correct address");
return false;
}
if (phone == "" || phone.length <= 9 || phone.length > 13 || isNaN(phone)) {
alert("Please enter correct phone");
return false;
}
return true;
}
function page3() {
var password = document.forms["form1"]["password"].value
var password2 = document.forms["form1"]["password"].value
if (password.match(/((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{8,15})/)) {
} else {
alert("Please enter correct password");
return false;
}
if (password1 != password2) {
alert("Password and Re-enter Password was not same");
return false;
}
return true;
}
$(document).ready(function() {
$(".form-wrapper .button1").click(function() {
if ($(this).hasClass('page1')) {
if (!page1()) {
return;
}
}
else if ($(this).hasClass('page2')) {
if (!page2()) {
return;
}
}
else if ($(this).hasClass('page3')) {
if (!page3()) {
return;
}
}
$(this).closest("form1").find("input[type=text], input[type=password]").val("");
var button = $(this);
var currentSection = button.parents(".section");
var currentSectionIndex = currentSection.index();
var headerSection = $('.steps li').eq(currentSectionIndex);
currentSection.removeClass("is-active").next().addClass("is-active");
headerSection.removeClass("is-active").next().addClass("is-active");
$(".form-wrapper").submit(function(e) {
e.preventDefault();
submit = $(this);
});
if (currentSectionIndex === 3) {
$(document).find(".form-wrapper .section").first().addClass("is-active");
$(document).find(".steps li").first().addClass("is-active");
}
});
});
$(document).ready(function() {
$(".form-wrapper .button2").click(function() {
var button = $(this);
var currentSection = button.parents(".section");
var currentSectionIndex = currentSection.index();
var headerSection = $('.steps li').eq(currentSectionIndex);
currentSection.removeClass("is-active").prev().addClass("is-active");
headerSection.removeClass("is-active").prev().addClass("is-active");
$(".form-wrapper").submit(function(e) {
e.preventDefault();
this.submit();
});
if (currentSectionIndex === 3) {
$(document).find(".form-wrapper .section").first().addClass("is-active");
$(document).find(".steps li").first().addClass("is-active");
}
});
});
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: 'Open Sans', sans-serif;
background-color: #fff;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: #fff;
font-weight: 200;
}
a {
text-decoration: none;
}
p,
li,
a {
font-size: 14px;
}
fieldset {
margin: 0;
padding: 0;
border: none;
color: #fff;
}
/* GRID */
.twelve {
width: 100%;
}
.eleven {
width: 91.53%;
}
.ten {
width: 83.06%;
}
.nine {
width: 74.6%;
}
.eight {
width: 66.13%;
}
.seven {
width: 57.66%;
}
.six {
width: 49.2%;
}
.five {
width: 40.73%;
}
.four {
width: 32.26%;
}
.three {
width: 23.8%;
}
.two {
width: 15.33%;
}
.one {
width: 6.866%;
}
/* COLUMNS */
.col {
display: block;
float: left;
margin: 0 0 0 1.6%;
}
.col:first-of-type {
margin-left: 0;
}
.container {
width: 100%;
max-width: 700px;
margin: 0 auto;
position: relative;
}
.row {
padding: 20px 0;
}
/* CLEARFIX */
.cf:before,
.cf:after {
content: " ";
display: table;
}
.cf:after {
clear: both;
}
.cf {
*zoom: 1;
}
.wrapper {
width: 100%;
margin: 30px 0;
}
/* STEPS */
.steps {
list-style-type: none;
margin: 0;
padding: 0;
background-color: #000;
text-align: center;
}
.steps li {
display: inline-block;
margin: 20px;
color: #ccc;
padding-bottom: 5px;
}
.steps li.is-active {
border-bottom: 1px solid #fff;
color: #fff;
}
/* FORM */
.form-wrapper .section {
padding: 0px 20px 30px 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
background-color: #000;
opacity: 0;
-webkit-transform: scale(1, 0);
-ms-transform: scale(1, 0);
-o-transform: scale(1, 0);
transform: scale(1, 0);
-webkit-transform-origin: top center;
-moz-transform-origin: top center;
-ms-transform-origin: top center;
-o-transform-origin: top center;
transform-origin: top center;
-webkit-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
text-align: center;
position: absolute;
width: 100%;
min-height: 300px
}
.form-wrapper .section h3 {
margin-bottom: 30px;
}
.form-wrapper .section.is-active {
opacity: 1;
-webkit-transform: scale(1, 1);
-ms-transform: scale(1, 1);
-o-transform: scale(1, 1);
transform: scale(1, 1);
}
.form-wrapper .button1,
.form-wrapper .submit {
background-color: #fff;
display: inline-block;
padding: 8px 30px;
color: #000;
cursor: pointer;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
position: absolute;
right: 20px;
bottom: 20px;
}
.form-wrapper .button2 {
background-color: #fff;
display: inline-block;
padding: 8px 30px;
color: #000;
cursor: pointer;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
position: absolute;
left: 20px;
bottom: 20px;
}
.form-wrapper .submit {
border: none;
outline: none;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.form-wrapper input[type="text"],
.form-wrapper input[type="password"] {
display: block;
padding: 10px;
margin: 10px auto;
background-color: #f1f1f1;
border: none;
width: 50%;
outline: none;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<div class="container">
<div class="wrapper">
<ul class="steps">
<li class="is-active">Step 1</li>
<li>Step 2</li>
<li>Step 3</li>
</ul>
<form class="form-wrapper" id="form1" onsumbit="return submit1()">
<fieldset class="section is-active">
<h3>Your Details</h3>
<input type="text" name="name" id="name" placeholder="Name">
<input type="text" name="email" id="email" placeholder="Email">
<input class="button1 page1" type="button" value="Next">
</fieldset>
<fieldset class="section">
<h3>other Details</h3>
<input type="text" name="phone" id="phone" placeholder="Phone">
<input type="text" name="address" id="address" placeholder="address">
<input class="button2" type="button" value="Previous">
<input class="button1 page2" type="button" value="Next" onclick="return page2()">
</fieldset>
<fieldset class="section">
<h3>Choose a Password</h3>
<input type="password" name="password" id="password" placeholder="Password">
<input type="password" name="password2" id="password2" placeholder="Re-enter Password">
<input class="button2" type="button" value="Previous">
<input class="submit button1 page3" type="submit" value="Sign Up" onclick="return page3()">
</fieldset>
<fieldset class="section">
<h3>Account Created!</h3>
<p>Your account has now been created.</p>
<div class="button1">Reset Form</div>
</fieldset>
</form>
</div>
</div>
by doing this you will be able to apply your code easily and you do not have to find multiple places to be appear.

Javascript php form validation issue

So here is my problem. if you follow the pictures. simple form. click on name. name moves up underline pulls across. you fill out name then go to next. It gives a nice background with checkmark. validation works great, but problem is with picture 5. after form is checked with php it comes back as errors which is great, but the blue background is gone and the text is behind the name placeholder. Does anyone have a solution to why this is happening?
resting
when clicked
when filled
when completed
error and name is hidden until clicked
clicked
The problem I am having is if the fill something out and forget to fill out a required field. The input they filled out is still there but hidden. You can see it if you click the field, but I would like it to stay like when you first fill it out. I know this may sound confusing thats why i am putting the code here. I hope someone out there could teach me some knowledge!
form.
<?php include('validate.php');?>
<?php include('header.php') ?>
<form id="contact_form" class="contact_form" action="contact.php"
id="contact_form" method="post">
<h2>Have a Question?</h2>
<div class="textinput <?php echo $nameErr ?>">
<?php
if(!empty($nameErr))
{
?>
<div class="requiredline">
</div>
<?php
}
?>
<div class="textinput ">
<input name="Name" type="text" id="Name"
placeholder="First & Last"
value="<?php echo (isset($Name) ? $Name : ""); ?>" />
<label for="Name">Name</label><div class="labelunderline"></div>
</div><span class='text_error'><?php echo $nameErr;?></span>
<div class="textinput <?php echo $nameErr ?>">
<?php
if(!empty($nameErr))
{
?>
<div class="requiredline">
</div>
<?php
}
?>
<div class="textinput">
<input name="Email" type="text" id="Email"
placeholder="Email#mail.com" value="<?php echo (isset($Email) ? $Email : ""); ?>" />
<label for="Email">Email</label>
<div class="labelunderline"></div><!--END LABEL UNDERLINE-->
</div><span class='text_error'><?php echo $emailErr;?></span>
<div class="textinput ">
<input type="text" id="Message" placeholder="Write what you feel" />
<label for="Message">Message</label><div class="labelunderline"></div>
</div>
<div class="input-wrap">
<button id="submit" name="submit" type="submit" value="SUBMIT"
class="col-xs-12 col-sm-8 col-md-6">Submit</button>
</div>
</form><!--END FORM-->
<?php include('footer.php') ?>
footer that holds the javascript for when option is filled.
<script>
$(".textinput input").change(function() {
if ($(this).val() != "") {
$(this).addClass('filled');
} else {
$(this).removeClass('filled');
}
})
</script>
</body>
</html>
css
body {
margin: 0;
padding: 0;
overflow-x: hidden;
}
/*============CONTACT PAGE=====================*/
#contact_header_text {
width: 100%;
height: 55vh;
padding-top: 135px;
font-family: Raleway-reg;
font-size: 2.5em;
color: white;
background-image:
linear-gradient(0deg, rgba(0, 79, 88, 0.5),
100%, rgba(0, 0, 0, 0.0)), url("../images/IMG_1464.jpg");
background-attachment: fixed;
background-repeat: no-repeat;
background-position: top center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-color: #dbdbdb;
}
#contact_section {
text-align: center;
font-size: 1.5em;
color: #333;
font-family: Raleway-reg;
background-color: #fff;
}
#contact_form {
max-width: 1200px;
margin: 0px auto 0px auto;
padding-top: 35px;
padding: 20px;
}
::-webkit-input-placeholder {
text-align: right;
font-family: Raleway-reg;
font-style: italic;
font-weight: bold;
color: #096771;
font-size: 15px;
}
::-moz-placeholder {
text-align: right;
font-family: Raleway-reg;
font-style: italic;
font-weight: bold;
color: #096771;
font-size: 15px;
}
button {
background: #3eacb8;
border: none;
border-radius: 2px;
color: #fff;
padding: 25px;
font-size: 14px;
font-weight: bold;
text-transform: uppercase;
text-align: center;
vertical-align: middle;
font-family: Raleway-med;
margin-bottom: 30px;
letter-spacing: 3px;
}
button:hover {
background-color: #096771;
transition: 0.5s all;
text-decoration: none;
letter-spacing: 6px;
}
label {
top: 10px;
position:absolute;
left: 35px;
transition: all 0.8s ease-in-out;
}
.textinput {
height: 3em;
margin: 1em 0;
position: relative;
width: 100%;
}
.textinput input,
.textinput label {
cursor: pointer;
font-size: 1.25em;
font-family: Raleway-reg;
text-align: left;
padding: 0.6em 1% 0.15em 1%;
/*
position: absolute;
*/
transition: all 0.15s ease;
width: 100%;
}
.labelunderline {
height: 1px;
width: 100%;
background-color: #3eacb8;
position: absolute;
bottom: 3px;
left: 0;
}
.textinput input {
text-decoration: none;
position: relative;
display: inline-block;
border-bottom: 3px solid transparent;
border-left: none;
border-top: none;
border-right: none;
width: 0%;
float: left;
transition: 0.5s ease;
white-space: nowrap;
}
.textinput input:focus {
border-bottom: 3px solid #096771;
width: 100%;
}
.textinput input.filled {
width: 100%;
}
.textinput label {
color: #3eacb8;
padding: 0.6em 0;
margin-left: -1em;
}
.textinput input.filled ~ label,
.textinput input:focus ~ label {
font-size: 0.6em;
font-weight: 600;
margin-top: -15px;
position: absolute;
}
.textinput input.filled ~ label {
color: #096771;
}
.textinput input[type="text"].filled,
.textinput input[type="email"].filled:valid {
background: #3eacb8;
color: white;
opacity: 0.4;
}
/*=================CHECKMARK========================*/
.textinput input[type="text"].filled ~label:after,
.textinput input[type="email"].filled:valid ~label:after {
color: #096771;
content: "\f058";
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: 3em;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
position: absolute;
top: 15px;
right: 35px;
transform: translate(0, 0);
}
.error {
/*
text-align: left;
margin-top: 5px;
*/
color: #FF0000;
font-family: pathwaygothic;
/*
display: block;
background-image:url(../images/x.png);
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
*/
}
.text_error {
text-align: left;
margin-top: -15px;
color: #FF0000;
display: block;
font-family: pathwaygothic;
background-image:url(../images/x.png);
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
}
div.error {
text-align: left;
font-size: 19px;
margin-top: 5px;
background-image:url(../images/x.png);
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
margin-left: 25px;
}
.requiredline {
height: 4px;
width: 100%;
position: absolute;
bottom: 0px;
left: 0;
background-color: red;
}
and lastly the validate form
<?php
session_start();
// define variables and set to empty values
$nameErr = $emailErr = $phoneErr = $describeErr = $humanErr = $subjectmatterErr = "";
$Name = $Email = $Phone = $Describe = $Human =
$Subjectmatter = "";
$hasError = false;
$sent = false;
if(isset($_POST['submit'])) {
$Name = trim(htmlspecialchars($_POST['Name'], ENT_QUOTES));
$Email = trim($_POST['Email']);
$Describe = trim(htmlspecialchars($_POST['Describe'], ENT_QUOTES));
$Phone = trim($_POST['Phone']);
$Company = trim($_POST['Company']);
$Website = trim($_POST['Website']);
$Subjectmatter = trim($_POST['Subjectmatter']);
$Human = trim($_POST['Human']);
$Number = 8;
$fieldsArray = array(
'Name' => $Name,
'Email' => $Email,
'Describe' => $Describe,
'Phone' => $Phone,
'subjectmatter' => $Subjectmatter,
'Human' => $Human
);
$errorArray = array();
foreach($fieldsArray as $key => $val) {
switch ($key) {
case 'Name':
if(empty($val)) {
$hasError = true;
$nameErr = "Please enter your name.";
}
case 'Name':
if (!preg_match("/^[a-zA-Z ]*$/", ($val))) {
$hasError = true;
$nameErr = "The value must be alphanumeric.";
}
break;
case 'Phone':
if (!preg_match("/^[0-9]+$/", ($val))) {
$hasError = true;
$phoneErr = "Only numbers and white space allowed.";
}
case 'Phone':
if(empty($val)) {
$hasError = true;
$phoneErr = "Phone is required.";
}
break;
case 'Subjectmatter':
if(empty($val)) {
$hasError = true;
$subjectmatterErr = "Subject is required.";
}
break;
case 'Email':
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$hasError = true;
$emailErr = "Email is required.";
} else {
$Email = filter_var($Email, FILTER_SANITIZE_EMAIL);
}
break;
case 'Describe' :
if (strlen($val) < 25) {
$hasError = true;
$describeErr = "Please enter at least 25 characters.
This way I know more specifically what you need!";
}
case 'Describe' :
if(empty($val)) {
$hasError = true;
$describeErr = "Message is required.
This way I know what you need!";
}
break;
case 'Human':
if (!preg_match("/[^\d]?8[^\d]?/", ($val))) {
$hasError = true;
$humanErr = "Not the right answer";
}
case 'Human':
if (!preg_match("/^[0-9]+$/", ($val))) {
$hasError = true;
$humanErr = "Must be a number";
}
case 'Human':
if(empty($val)) {
$hasError = true;
$humanErr = "Are you human?";
}
break;
}
}
//Validation Success!
//Do form processing like email, database etc here
if($hasError !== true) {
$priority = $_POST['priority'];
$type = $_POST['type'];
$message = $_POST['message'];
$formcontent=" From: $Name \n Company: $Company \n
Email: $Email \n Phone: $Phone \n
Website: $Website \n Subject: $Subjectmatter
\n Describe: $Describe \n\n";
$recipient = "email#email.com";
$subject = "Contact Form";
$mailheader = "From: $Email \r\n";
mail($recipient, $subject, $formcontent,
$mailheader /*$message, $headers*/);
header("Refresh:0; url=thanks.php");
exit();
}
}
?><!--END PHP-->
I know someone can figure out where i screwed up!
The problem is that the blue background comes from the change event handler, which adds and removes the class 'filled' to the input, but when you reload the page nobody calls it.
To let things easy I suggest that you refactor your javascript and call it on
$(document).ready.
Try this
$(document).ready(function(){
function checkInput(elem){
if ($(elem).val() != "") {
$(elem).addClass('filled');
} else {
$(elem).removeClass('filled');
}
}
$(".textinput input").change(function() {
checkInput(this);
});
$(".textinput input").each(function(){
checkInput(this);
});
}
Otherwise you can do it in the php side. Then on every input you've to check whether the field has a values with issetand add the class to the input.
Fiddle

Categories