Login form validation with error messages - javascript

I'm trying to make a login form that check if my data are correct.
For example, if I insert a different value than "new_user" in the username field, then it should display a red error message under the submit button saying "please insert a valid user", and the border of the input field should be red as well.
If the username field is empty it has to do the same thing, just that the error message now has to be "please insert a username" and the same thing has to apply for the password field.
If the values for both username and password are matching has to display the message "Successfully Login"
I will attach an image just as an example, and I have added my code below. Please feel free to tell me what am I doing wrong.
var form = document.getElementById("form");
var user = document.getElementById("username");
var pass = document.getElementById("password");
var botton = document.getElementById("btn")
var validUser = "new_user";
var validPassword = 123456789;
form.addEventListener("submit", function(e) {
e.preventDefault();
checkInputs();
})
user.addEventListener("input", function() {
var username = user.value;
if (username) {
if (username === " " || username == null) {
setErrorFor(user, "Please insert a username");
} else if (username !== validUser) {
setErrorFor(user, "Please insert a valid username");
}
} else {
setSuccessFor(user, "Successfully Login")
}
})
function setErrorFor(input, message) {
var formControl = input.parentElement;
var showError = document.querySelector(".text-message");
var displayMessage = document.getElementById("msg");
//add error message & add the class name inside the message element
displayMessage.innerHTML = message
showError.className = "text-message invalid"
//add the error class
formControl.classList = "form-control fail"
}
function setSuccessFor(input, message) {
var formControl = input.parentElement;
var showError = document.querySelector(".text-message");
var displayMessage = document.getElementById("msg");
//add error message & add the class name inside the message element
displayMessage.innerHTML = message
showError.className = "text-message valid"
//add the error class
formControl.classList = "form-control success"
}
* {
box-sizing: border-box;
font-family: sans-serif;
}
body {
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
}
#login-container {
width: 45%;
margin: 0 auto;
border-radius: .5em;
position: relative;
background: linear-gradient(to right, rgb(88, 167, 236), rgb(180, 198, 214), rgb(180, 198, 214));
padding: 3em 2.5em;
box-shadow: 0px 5px 4px #424241;
text-align: justify;
}
.input-field {
margin-bottom: .5em;
}
input[type="text"],
input[type="password"] {
width: 100%;
display: inline-block;
outline: none;
font-size: 18px;
padding: .5em 1.5em .5em .5em;
border-radius: .5em;
}
.form-control {
position: relative;
}
.input-field i {
position: absolute;
top: 2.2em;
right: .5em;
opacity: 0;
}
.fa-check {
color: green;
}
.fa-times {
color: red;
}
form label {
font-weight: bold;
display: inline-block;
font-size: 18px;
margin-bottom: .2em;
}
form input[type="submit"] {
background: rgb(112, 112, 112);
border-radius: .5em;
margin: 1em 0 .2em 0;
padding: .5em 0;
display: block;
font-size: 18px;
font-weight: 700;
width: 100%;
position: relative;
text-transform: uppercase;
border: none;
}
form input[type="submit"]:hover {
background-color: #70db70;
color: white;
}
.text-message .msg {
margin: 0;
padding: 0;
font-size: 16px;
}
/*Message classes*/
.form-control.success input {
border: 3px solid green;
}
.form-control.fail input {
border: 3px solid red;
}
.form-control.success i.fa-check {
opacity: 1;
}
.form-control.fail i.fa-times {
opacity: 1;
}
.text-message.valid p {
display: block;
color: green;
}
.text-message.invalid p {
display: block;
color: red;
}
<form id="form">
<div class="input-field">
<div class="form-control">
<label for="username">Username:</label>
<input id="username" class="input" type="text">
<i class="fas fa-check u_check"></i>
<i class="fas fa-times u_decline"></i>
</div>
</div>
<div class="input-field">
<div class="form-control">
<label for="password">Password:</label>
<input id="password" class="input" type="password">
<i class="fas fa-check p_check"></i>
<i class="fas fa-times p_decline"></i>
</div>
</div>
<input type="submit" value="submit" id="btn">
<div class="text-message">
<p id="msg" class="msg"></p>
</div>

Related

Contact form javascript and php

First of all, I'm new to website creation and especially to php.
I have created a contact form for my website with a validation and a message that is displayed if everything is filled in correctly (see the snippet below). I know that the validation has to be done on both the client and server side, but I know that I am dealing with something else.
I have created a php file that works: I get the email when the user clicks submit.
I am faced with two things.
How do I keep the javascript validation and the message on the front end?
How do I configure the php to stay on the page, or better yet, run in the back and only submit the form to my email?
<?php
if(isset($_POST['submit'])){
$mailto = "contact#statsmap.ch"; //Send the email to this adress
//All the inputs informations
$mailfrom = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
//$message = "NAME: " .$name. "\r\n\n". "Wrote the following Message:" ."\r\n". $_POST['message'];
$message = $_POST['message'];
$headers = "From: ". $mailfrom;
$sendMail = mail($mailto, $subject, $message, $headers); // Send mail to website owner
}
?>
const form = document.getElementById('formContact');
const nameContact = document.getElementById('name');
const emailContact = document.getElementById('email');
const messageContact = document.getElementById('message');
const headerContact = document.querySelector('.headerContact')
const thankYou = document.querySelector('.Thankyou');
const isValidEmail = (email) => {
const 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(String(email).toLowerCase());
};
let isValid = true;
function checkInputs(){
//get the values from the inputs or textarea
const nameValue = nameContact.value.trim();
const emailValue = emailContact.value.trim();
const messageValue = messageContact.value.trim();
if (nameValue === ''){
//show error
//add error class
setErrorFor(nameContact, 'Name cannot be blank');
} else{
//add success class
setSuccesFor(nameContact);
}
if (emailValue === ''){
//show error
//add error class
setErrorFor(emailContact, 'Email cannot be blank');
} else if(!isValidEmail(emailValue)){
setErrorFor(emailContact, 'Please add a valid email adress');
} else{
setSuccesFor(emailContact);
}
if (messageValue === ''){
//show error
//add error class
setErrorFor(messageContact, 'Message cannot be blank');
} else if (messageValue.length < 20){
setErrorFor(messageContact, 'Message need to be at least 20 characters');
}
else{
//add success class
setSuccesFor(messageContact);
}
}
function setErrorFor(input, message){
isValid=false;
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//add error message inside the span
errorContactMessage.innerText = message;
//add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input){
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//remove message inside the span
errorContactMessage.innerText='';
//add success class
formControl.className = 'form-control success';
}
let nameThk = "";
nameContact.addEventListener('input', (e) =>{
nameThk = e.target.value;
});
form.addEventListener('submit', () =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
}
});
.containerContact {
background-color: #F8F8F8;
width: 100%;
max-width: 100%;
padding: 0.5rem;
display: block;
}
.containerContact h2 {
margin-bottom: 0.5rem;
}
.form-control {
margin-bottom: 0.25rem;
position: relative;
}
.form-control input {
display: block;
width: 100%;
height: 2rem;
padding-left: 0.5rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-size: 0.8125rem;
color: #000000;
}
.form-control input::-webkit-input-placeholder {
color: #000000;
}
.form-control input:-ms-input-placeholder {
color: #000000;
}
.form-control input::-ms-input-placeholder {
color: #000000;
}
.form-control input::placeholder {
color: #000000;
}
.form-control textarea {
width: 100%;
height: 10rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-family: Arial, Helvetica, sans-serif;
padding: 0.5rem;
font-size: 0.8125rem;
color: #000000;
resize: none;
}
.form-control textarea::-webkit-input-placeholder {
color: #000000;
}
.form-control textarea:-ms-input-placeholder {
color: #000000;
}
.form-control textarea::-ms-input-placeholder {
color: #000000;
}
.form-control textarea::placeholder {
color: #000000;
}
.form-control i {
position: absolute;
top: 0.5rem;
right: 0.5rem;
visibility: hidden;
}
.form-control #textareaChecks {
position: absolute;
top: 8.5rem;
right: 0.5rem;
}
.form-control.success input {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error input {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.success textarea {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error textarea {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
#Error {
font-weight: 500;
font-size: 0.75rem;
font-style: italic;
color: red;
margin: 0;
padding: 0;
}
#ContactSubmit {
width: 100%;
height: 2rem;
background: #1e1e1e;
outline: none;
border: 0.025rem solid #000000;
color: #FFFFFF;
}
.containerThank {
height: 300px;
display: -ms-grid;
display: grid;
}
.containerThank h3 {
margin: 0;
text-align: center;
-ms-flex-item-align: end;
align-self: flex-end;
font-size: 18px;
font-weight: bold;
}
.containerThank p {
-ms-flex-item-align: start;
align-self: flex-start;
text-align: center;
font-size: 13px;
padding-top: 0.5rem;
}
.hide {
display: none;
}
<form action="/php/contactMail.php" method="POST" class="formContact" id="formContact" novalidate>
<div class="form-control">
<input type="text" name="name" id="name" placeholder="First and Last name">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="email" name="email" id="email" placeholder="Please enter your email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="text" name="subject" id="subject" placeholder="Subject">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<textarea id="message" name="message" type="text" placeholder="Message"></textarea>
<i id="textareaChecks" class="fas fa-check-circle"></i>
<i id="textareaChecks" class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<button id="ContactSubmit" name="submit">Submit</button>
</form>
<div class="Thankyou hide">
<div class="containerThank">
<h3 id="merci"></h3>
<p>Our team is going to get back to you as soon as possible</p>
</div>
</div>
</div>
</div>
</section>
</div>
Looks like you checked the variable isValid for it to be true, but you didn't provide an alternative if isValid is false.
Basically, I edited this:
form.addEventListener('submit', (e) =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
} else {
e.preventDefault()
}
As you can see, if isValid is false, the script prevents the form from submitting.
Working snippet:
const form = document.getElementById('formContact');
const nameContact = document.getElementById('name');
const emailContact = document.getElementById('email');
const messageContact = document.getElementById('message');
const headerContact = document.querySelector('.headerContact')
const thankYou = document.querySelector('.Thankyou');
const isValidEmail = (email) => {
const 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(String(email).toLowerCase());
};
let isValid = true;
function checkInputs(){
//get the values from the inputs or textarea
const nameValue = nameContact.value.trim();
const emailValue = emailContact.value.trim();
const messageValue = messageContact.value.trim();
if (nameValue === ''){
//show error
//add error class
setErrorFor(nameContact, 'Name cannot be blank');
} else{
//add success class
setSuccesFor(nameContact);
}
if (emailValue === ''){
//show error
//add error class
setErrorFor(emailContact, 'Email cannot be blank');
} else if(!isValidEmail(emailValue)){
setErrorFor(emailContact, 'Please add a valid email adress');
} else{
setSuccesFor(emailContact);
}
if (messageValue === ''){
//show error
//add error class
setErrorFor(messageContact, 'Message cannot be blank');
} else if (messageValue.length < 20){
setErrorFor(messageContact, 'Message need to be at least 20 characters');
}
else{
//add success class
setSuccesFor(messageContact);
}
}
function setErrorFor(input, message){
isValid=false;
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//add error message inside the span
errorContactMessage.innerText = message;
//add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input){
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//remove message inside the span
errorContactMessage.innerText='';
//add success class
formControl.className = 'form-control success';
}
let nameThk = "";
nameContact.addEventListener('input', (e) =>{
nameThk = e.target.value;
});
form.addEventListener('submit', (e) =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
} else {
e.preventDefault()
}
});
.containerContact {
background-color: #F8F8F8;
width: 100%;
max-width: 100%;
padding: 0.5rem;
display: block;
}
.containerContact h2 {
margin-bottom: 0.5rem;
}
.form-control {
margin-bottom: 0.25rem;
position: relative;
}
.form-control input {
display: block;
width: 100%;
height: 2rem;
padding-left: 0.5rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-size: 0.8125rem;
color: #000000;
}
.form-control input::-webkit-input-placeholder {
color: #000000;
}
.form-control input:-ms-input-placeholder {
color: #000000;
}
.form-control input::-ms-input-placeholder {
color: #000000;
}
.form-control input::placeholder {
color: #000000;
}
.form-control textarea {
width: 100%;
height: 10rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-family: Arial, Helvetica, sans-serif;
padding: 0.5rem;
font-size: 0.8125rem;
color: #000000;
resize: none;
}
.form-control textarea::-webkit-input-placeholder {
color: #000000;
}
.form-control textarea:-ms-input-placeholder {
color: #000000;
}
.form-control textarea::-ms-input-placeholder {
color: #000000;
}
.form-control textarea::placeholder {
color: #000000;
}
.form-control i {
position: absolute;
top: 0.5rem;
right: 0.5rem;
visibility: hidden;
}
.form-control #textareaChecks {
position: absolute;
top: 8.5rem;
right: 0.5rem;
}
.form-control.success input {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error input {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.success textarea {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error textarea {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
#Error {
font-weight: 500;
font-size: 0.75rem;
font-style: italic;
color: red;
margin: 0;
padding: 0;
}
#ContactSubmit {
width: 100%;
height: 2rem;
background: #1e1e1e;
outline: none;
border: 0.025rem solid #000000;
color: #FFFFFF;
}
.containerThank {
height: 300px;
display: -ms-grid;
display: grid;
}
.containerThank h3 {
margin: 0;
text-align: center;
-ms-flex-item-align: end;
align-self: flex-end;
font-size: 18px;
font-weight: bold;
}
.containerThank p {
-ms-flex-item-align: start;
align-self: flex-start;
text-align: center;
font-size: 13px;
padding-top: 0.5rem;
}
.hide {
display: none;
}
<form action="/php/contactMail.php" method="POST" class="formContact" id="formContact" novalidate>
<div class="form-control">
<input type="text" name="name" id="name" placeholder="First and Last name">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="email" name="email" id="email" placeholder="Please enter your email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="text" name="subject" id="subject" placeholder="Subject">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<textarea id="message" name="message" type="text" placeholder="Message"></textarea>
<i id="textareaChecks" class="fas fa-check-circle"></i>
<i id="textareaChecks" class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<button id="ContactSubmit" name="submit">Submit</button>
</form>
<div class="Thankyou hide">
<div class="containerThank">
<h3 id="merci"></h3>
<p>Our team is going to get back to you as soon as possible</p>
</div>
</div>
</div>
</div>
</section>
</div>

How to I add error messages as per the error in HTML

Currently the Error message that is displayed is common for all the errors . But i want to display different error messages for different errors. Like for Invalid password it should display invalid password. Whereas for invalid username it should display invalid username.
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
font-family: Arial, Helvetica, sans-serif;
display: grid;
justify-items: center;
align-items: center;
background-color: #d39090;
}
#main-holder {
width: 50%;
height: 70%;
display: grid;
justify-items: center;
align-items: center;
background-color: white;
border-radius: 7px;
box-shadow: 0px 0px 5px 2px black;
}
#signup-error-msg-holder {
width: 100%;
height: 100%;
display: grid;
justify-items: center;
align-items: center;
}
#signup-error-msg {
width: 23%;
text-align: center;
margin: 0;
padding: 5px;
font-size: 16px;
font-weight: bold;
color: #8a0000;
border: 1px solid #8a0000;
background-color: #e58f8f;
opacity: 0;
}
#error-msg-second-line {
display: block;
}
#signup-form {
align-self: flex-start;
display: grid;
justify-items: center;
align-items: center;
}
.signup-form-field::placeholder {
color: #2e4136;
}
.signup-form-field {
border: none;
border-bottom: 1px solid #755ddf;
margin-bottom: 10px;
border-radius: 3px;
outline: none;
padding: 0px 0px 5px 5px;
}
#signup-form-submit {
width: 100%;
margin-top: 20px;
padding: 10px;
border: none;
border-radius: 5px;
color: white;
font-weight: bold;
background-color: #43509b;
cursor: pointer;
outline: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign Up Page</title>
<link rel="stylesheet" href="interlog.css">
</head>
<body>
<main id="main-holder">
<h1 id="signup-header"><b>Sign Up</b></h1>
<div id="signup-error-msg-holder">
<p id="signup-error-msg">Invalid username <span id="error-msg-second-line">and/or password</span></p>
</div>
<form id="signup-form">
<input type="text" name="username" id="username-field" class="signup-form-field" placeholder="Username">
<input type="password" name="password" id="password-field" class="signup-form-field" placeholder="Password">
<input type="submit" value="submit" id="signup-form-submit">
</form>
</main>
<script>
const signupForm = document.getElementById("signup-form");
const signupButton = document.getElementById("signup-form-submit");
const signupErrorMsg = document.getElementById("signup-error-msg");
signupButton.addEventListener("click", (e) => {
e.preventDefault();
const username = signupForm.username.value;
const password = signupForm.password.value;
if (username === "admin" && password === "password") {
alert("You have successfully logged in.");
location.reload();
} else {
signupErrorMsg.style.opacity = 1;
}
})
</script>
</body>
</html>
Can someone Please tell me How should i do that. I tried adding another message at and making the necessary changes in javascript, but it would display both messages simultaneously.
`<div id="signup-error-msg-holder">
<p id="signup-error-msg1">Invalid password</p>
</div>
<div id="signup-error-msg-holder">
<p id="signup-error-msg2">Invalid username </p>
</div>
`
const signupErrorMsg1 = document.getElementById("signup-error-msg1");
const signupErrorMsg2 = document.getElementById("signup-error-msg2");
signupButton.addEventListener("click", (e) => {
e.preventDefault();
const username = signupForm.username.value;
const password = signupForm.password.value;
if (username === "admin" && password === "password") {
alert("You have successfully logged in.");
location.reload();
} else if (username === "admin" && password !== "password") {
signupErrorMsg1.style.opacity = 1;
} else if (username !== "admin" && password === "password") {
signupErrorMsg2.style.opacity = 1;
}
})
`
Any help would be appreciated .
Test each and push to an error array. If the array has zero length the tests passed
const signupForm = document.getElementById("signup-form");
const signupButton = document.getElementById("signup-form-submit");
const signupErrorMsg = document.getElementById("signup-error-msg");
signupButton.addEventListener("click", (e) => {
e.preventDefault();
const username = signupForm.username.value;
const password = signupForm.password.value;
const msg = []
if (username !== "admin") msg.push("username")
if (password !== "password") msg.push("password")
if (msg.length === 0) {
alert("You have successfully logged in.");
location.reload();
return;
}
signupErrorMsg.textContent = "Invalid " + msg.join(" and ");
signupErrorMsg.style.opacity = 1;
})
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
font-family: Arial, Helvetica, sans-serif;
display: grid;
justify-items: center;
align-items: center;
background-color: #d39090;
}
#main-holder {
width: 50%;
height: 70%;
display: grid;
justify-items: center;
align-items: center;
background-color: white;
border-radius: 7px;
box-shadow: 0px 0px 5px 2px black;
}
#signup-error-msg-holder {
width: 100%;
height: 100%;
display: grid;
justify-items: center;
align-items: center;
}
#signup-error-msg {
width: 23%;
text-align: center;
margin: 0;
padding: 5px;
font-size: 16px;
font-weight: bold;
color: #8a0000;
border: 1px solid #8a0000;
background-color: #e58f8f;
opacity: 0;
}
#error-msg-second-line {
display: block;
}
#signup-form {
align-self: flex-start;
display: grid;
justify-items: center;
align-items: center;
}
.signup-form-field::placeholder {
color: #2e4136;
}
.signup-form-field {
border: none;
border-bottom: 1px solid #755ddf;
margin-bottom: 10px;
border-radius: 3px;
outline: none;
padding: 0px 0px 5px 5px;
}
#signup-form-submit {
width: 100%;
margin-top: 20px;
padding: 10px;
border: none;
border-radius: 5px;
color: white;
font-weight: bold;
background-color: #43509b;
cursor: pointer;
outline: none;
}
<main id="main-holder">
<h1 id="signup-header"><b>Sign Up</b></h1>
<div id="signup-error-msg-holder">
<p id="signup-error-msg"></p>
</div>
<form id="signup-form">
<input type="text" name="username" id="username-field" class="signup-form-field" placeholder="Username">
<input type="password" name="password" id="password-field" class="signup-form-field" placeholder="Password">
<input type="submit" value="submit" id="signup-form-submit">
</form>
</main>

Need Help altering a clone to-do list to make it log 3 outputs instead of one (javascript/html/css/JSON)

I began to change the copied code, so that instead of it being a "to-do" list that shoots out one statement at a time, I wanted to change it to shoot out 3 statements at a time and log them in a row.
I was able to add 2 more boxes, but when I press the purple button to have it run, it logs only one of the boxes and it leaves writing in the other 2 (new boxes I made) and it ends up looking like this before pressing the purple button:
enter image description here
and this logs out as a result :
enter image description here
just the name, but email does not and it leaves an imprint of the email and date (unlike the 'user name box')
Tried tinkering with eth code but don't understand how to manipulate it to make it show what I want and log the three things. Can you please help show me how to do this. Below are 3 files for HTML, CSS, and JS.
// getting all required elements
const inputBox = document.querySelector(".inputField input");
const addBtn = document.querySelector(".inputField button");
const todoList = document.querySelector(".todoList");
const deleteAllBtn = document.querySelector(".footer button");
// onkeyup event
inputBox.onkeyup = ()=>{
let userEnteredValue = inputBox.value; //getting user entered value
if(userEnteredValue.trim() != 0){ //if the user value isn't only spaces
addBtn.classList.add("active"); //active the add button
}else{
addBtn.classList.remove("active"); //unactive the add button
}
}
showTasks(); //calling showTask function
addBtn.onclick = ()=>{ //when user click on plus icon button
let userEnteredValue = inputBox.value; //getting input field value
let getLocalStorageData = localStorage.getItem("New Todo"); //getting localstorage
if(getLocalStorageData == null){ //if localstorage has no data
listArray = []; //create a blank array
}else{
listArray = JSON.parse(getLocalStorageData); //transforming json string into a js object
}
listArray.push(userEnteredValue); //pushing or adding new value in array
localStorage.setItem("New Todo", JSON.stringify(listArray)); //transforming js object into a json string
showTasks(); //calling showTask function
addBtn.classList.remove("active"); //unactive the add button once the task added
}
function showTasks(){
let getLocalStorageData = localStorage.getItem("New Todo");
if(getLocalStorageData == null){
listArray = [];
}else{
listArray = JSON.parse(getLocalStorageData);
}
const pendingTasksNumb = document.querySelector(".pendingTasks");
pendingTasksNumb.textContent = listArray.length; //passing the array length in pendingtask
if(listArray.length > 0){ //if array length is greater than 0
deleteAllBtn.classList.add("active"); //active the delete button
}else{
deleteAllBtn.classList.remove("active"); //unactive the delete button
}
let newLiTag = "";
listArray.forEach((element, index) => {
newLiTag += `<li>${element}<span class="icon" onclick="deleteTask(${index})"><i class="fas fa-trash"></i></span></li>`;
});
todoList.innerHTML = newLiTag; //adding new li tag inside ul tag
inputBox.value = ""; //once task added leave the input field blank
}
// delete task function
function deleteTask(index){
let getLocalStorageData = localStorage.getItem("New Todo");
listArray = JSON.parse(getLocalStorageData);
listArray.splice(index, 1); //delete or remove the li
localStorage.setItem("New Todo", JSON.stringify(listArray));
showTasks(); //call the showTasks function
}
// delete all tasks function
deleteAllBtn.onclick = ()=>{
listArray = []; //empty the array
localStorage.setItem("New Todo", JSON.stringify(listArray)); //set the item in localstorage
showTasks(); //call the showTasks function
}
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#200;300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
::selection{
color: #ffff;
background: rgb(142, 73, 232);
}
body{
width: 100%;
height: 100vh;
/* overflow: hidden; */
padding: 10px;
background: linear-gradient(to bottom, #68EACC 0%, #497BE8 100%);
}
.wrapper{
background: #fff;
max-width: 1200px;
width: 100%;
margin: 120px auto;
padding: 25px;
border-radius: 5px;
box-shadow: 0px 10px 15px rgba(0,0,0,0.1);
}
.wrapper header{
font-size: 30px;
font-weight: 600;
}
.wrapper .inputField{
margin: 20px 0;
width: 100%;
display: flex;
height: 45px;
}
.inputField input{
width: 85%;
height: 100%;
outline: none;
border-radius: 3px;
border: 1px solid #ccc;
font-size: 17px;
padding-left: 15px;
transition: all 0.3s ease;
}
.inputField input:focus{
border-color: #8E49E8;
}
.inputField button{
width: 100px;
height: 100%;
border: none;
color: #fff;
margin-left: 5px;
font-size: 21px;
outline: none;
background: #8E49E8;
cursor: pointer;
border-radius: 3px;
opacity: 0.6;
pointer-events: none;
transition: all 0.3s ease;
}
.inputField button:hover,
.footer button:hover{
background: #721ce3;
}
.inputField button.active{
opacity: 1;
pointer-events: auto;
}
.wrapper .todoList{
max-height: 250px;
overflow-y: auto;
}
.todoList li{
position: relative;
list-style: none;
height: 45px;
line-height: 45px;
margin-bottom: 8px;
background: #f2f2f2;
border-radius: 3px;
padding: 0 15px;
cursor: default;
overflow: hidden;
}
.todoList li .icon{
position: absolute;
right: -45px;
background: #e74c3c;
width: 45px;
text-align: center;
color: #fff;
border-radius: 0 3px 3px 0;
cursor: pointer;
transition: all 0.2s ease;
}
.todoList li:hover .icon{
right: 0px;
}
.wrapper .footer{
display: flex;
width: 100%;
margin-top: 20px;
align-items: center;
justify-content: space-between;
}
.footer button{
padding: 6px 10px;
border-radius: 3px;
border: none;
outline: none;
color: #fff;
font-weight: 400;
font-size: 16px;
margin-left: 5px;
background: #8E49E8;
cursor: pointer;
user-select: none;
opacity: 0.6;
pointer-events: none;
transition: all 0.3s ease;
}
.footer button.active{
opacity: 1;
pointer-events: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do App</title>
<link rel="stylesheet" href="todo.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
<div class="wrapper">
<header>Support Tickets</header>
<div class="inputField" >
<input type="text" placeholder="Users Name" required>
<input type="email" placeholder="Users Email" required>
<input type="text" placeholder="Date" required>
<button><i class="fas fa-plus"></i></button>
</div>
<ul class="todoList">
<!-- data are comes from local storage -->
</ul>
<div class="footer">
<span>You have <span class="pendingTasks"></span> pending tasks</span>
<button>Clear All</button>
</div>
</div>
<script src="todo.js"></script>
</body>
</html>
First of all you never used the value of email and date and hence only the name was being displayed.
I made a few changes to your listArray structure and made it an object, something like this
let userEnteredValue = {
name: inputBox.value,
email: email.value,
date: date.value
};
for better understanding and code readability.
Then I made a few changes to your css to to display it in a line.
Also i added a button in place of trash can icon because, I don't have bootstrap but you can replace the button with the icon again
const inputBox = document.querySelector(".inputField input");
const email = document.querySelector("#email");
const date = document.querySelector("#date");
const addBtn = document.querySelector(".inputField button");
const todoList = document.querySelector(".todoList");
const deleteAllBtn = document.querySelector(".footer button");
// onkeyup event
inputBox.onkeyup = () => {
let userEnteredValue = inputBox.value; //getting user entered value
if (userEnteredValue.trim() != 0) {
//if the user value isn't only spaces
addBtn.classList.add("active"); //active the add button
} else {
addBtn.classList.remove("active"); //unactive the add button
}
};
showTasks(); //calling showTask function
addBtn.onclick = () => {
//when user click on plus icon button
let userEnteredValue = {
name: inputBox.value,
email: email.value,
date: date.value,
}; //getting input field value
console.log(userEnteredValue);
let getLocalStorageData = localStorage.getItem("New Todo"); //getting localstorage
if (getLocalStorageData == null) {
//if localstorage has no data
listArray = []; //create a blank array
} else {
listArray = JSON.parse(getLocalStorageData); //transforming json string into a js object
}
listArray.push(userEnteredValue); //pushing or adding new value in array
localStorage.setItem("New Todo", JSON.stringify(listArray)); //transforming js object into a json string
showTasks(); //calling showTask function
addBtn.classList.remove("active"); //unactive the add button once the task added
};
function showTasks() {
todoList.innerHTML = "";
let getLocalStorageData = localStorage.getItem("New Todo");
if (getLocalStorageData == null) {
listArray = [];
} else {
listArray = JSON.parse(getLocalStorageData);
}
const pendingTasksNumb = document.querySelector(".pendingTasks");
pendingTasksNumb.textContent = listArray.length; //passing the array length in pendingtask
if (listArray.length > 0) {
//if array length is greater than 0
deleteAllBtn.classList.add("active"); //active the delete button
} else {
deleteAllBtn.classList.remove("active"); //unactive the delete button
}
// console.log(listArray);
listArray.forEach((element, index) => {
let newLiTag = "";
newLiTag = `<li>${element.name} ${element.email} ${element.date}<span class="icon" onclick="deleteTask(${index})"><button>Delete</button></span></li><br>`;
todoList.insertAdjacentHTML("afterbegin", newLiTag); //adding new li tag inside ul tag
});
// console.log(newLiTag);
inputBox.value = "";
email.value = "";
date.value = ""; //once task added leave the input field blank
}
// delete task function
function deleteTask(index) {
let getLocalStorageData = localStorage.getItem("New Todo");
listArray = JSON.parse(getLocalStorageData);
console.log(listArray);
listArray.splice(index, 1); //delete or remove the li
localStorage.setItem("New Todo", JSON.stringify(listArray));
showTasks(); //call the showTasks function
}
// delete all tasks function
deleteAllBtn.onclick = () => {
todoList.innerHTML = "";
listArray = []; //empty the array
localStorage.setItem("New Todo", JSON.stringify(listArray)); //set the item in localstorage
showTasks(); //call the showTasks function
};
#import url("https://fonts.googleapis.com/css2?family=Poppins:wght#200;300;400;500;600;700&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
::selection {
color: #ffff;
background: rgb(142, 73, 232);
}
body {
width: 100%;
height: 100vh;
/* overflow: hidden; */
padding: 10px;
background: linear-gradient(to bottom, #68eacc 0%, #497be8 100%);
}
.wrapper {
background: #fff;
max-width: 1200px;
width: 100%;
margin: 120px auto;
padding: 25px;
border-radius: 5px;
box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.1);
}
.wrapper header {
font-size: 30px;
font-weight: 600;
}
.wrapper .inputField {
margin: 20px 0;
width: 100%;
display: flex;
height: 45px;
}
.inputField input {
width: 85%;
height: 100%;
outline: none;
border-radius: 3px;
border: 1px solid #ccc;
font-size: 17px;
padding-left: 15px;
transition: all 0.3s ease;
}
.inputField input:focus {
border-color: #8e49e8;
}
.inputField button {
width: 100px;
height: 100%;
border: none;
color: #fff;
margin-left: 5px;
font-size: 21px;
outline: none;
background: #8e49e8;
cursor: pointer;
border-radius: 3px;
opacity: 0.6;
pointer-events: none;
transition: all 0.3s ease;
}
.inputField button:hover,
.footer button:hover {
background: #721ce3;
}
.inputField button.active {
opacity: 1;
pointer-events: auto;
}
.wrapper .todoList {
max-height: 250px;
overflow-y: auto;
}
.todoList li {
position: relative;
list-style: none;
height: 45px;
line-height: 45px;
margin-bottom: 8px;
background: #f2f2f2;
border-radius: 3px;
padding: 0 15px;
cursor: default;
overflow: hidden;
}
.todoList li .icon {
position: absolute;
right: -45px;
background: #e74c3c;
width: 45px;
text-align: center;
color: #fff;
border-radius: 0 3px 3px 0;
cursor: pointer;
transition: all 0.2s ease;
}
.todoList li:hover .icon {
right: 20px;
}
.wrapper .footer {
display: flex;
width: 100%;
margin-top: 20px;
align-items: center;
justify-content: space-between;
}
.footer button {
padding: 6px 10px;
border-radius: 3px;
border: none;
outline: none;
color: #fff;
font-weight: 400;
font-size: 16px;
margin-left: 5px;
background: #8e49e8;
cursor: pointer;
user-select: none;
opacity: 0.6;
pointer-events: none;
transition: all 0.3s ease;
}
.footer button.active {
opacity: 1;
pointer-events: auto;
}
.todoList li {
font-size: 25px;
width: 100%;
display: block;
word-spacing: 250px;
}
<div class="wrapper">
<header>Support Tickets</header>
<div class="inputField">
<input type="text" id="name" placeholder="Users Name" required />
<input type="email" id="email" placeholder="Users Email" required />
<input type="text" id="date" placeholder="Date" required />
<button><i class="fas fa-plus"></i></button>
</div>
<ul class="todoList">
<!-- data are comes from local storage -->
</ul>
<div class="footer">
<span>You have <span class="pendingTasks"></span> pending tasks</span>
<button>Clear All</button>
</div>
</div>
Since localStorage won't run in this snippet below is a output screenshot
Now,everyting works just as you want them to!!
Also your code, which I edited needs a lot of refactoring for better readability and efficiency.....

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
}

How to use contents of h2 tag as subject of email?

I would like my subject to change according to the specific button pressed. Each button represents a different order choice, and changes the value of the h2 tag. I would like the contents of this h2 tag to be the subject of my email in PHP. How do I do this?
// JavaScript Document
// Validating Empty Field
//function check_empty() {
//if (document.getElementById('name').value == "" || document.getElementById('email').value == "") {
//alert("Please fill out all fields.");
//} else {
// alert("Order Successful!");
//}
//}
//Function To Display Popup
function div_show1() {
document.getElementById("ordertype").innerHTML = "$400 Website Order";
document.getElementById('abc').style.display = "block";
}
function div_show2() {
document.getElementById("ordertype").innerHTML = "$500 Website Order";
document.getElementById('abc').style.display = "block";
}
function div_show3() {
document.getElementById("ordertype").innerHTML = "$700 Website Order";
document.getElementById('abc').style.display = "block";
}
//Function to Hide Popup
function div_hide() {
document.getElementById('abc').style.display = "none";
}
#charset "utf-8";
/* CSS Document */
#abc {
width: 100%;
height: 100%;
opacity: 0.97;
top: 0;
left: 0;
display: none;
position: fixed;
background-color: #313131;
overflow: auto;
z-index: 9999999;
}
img#close {
position: absolute;
right: -14px;
top: -14px;
cursor: pointer;
}
div#popupContact {
position: absolute;
left: 50%;
top: 17%;
margin-left: -202px;
font-family: coolfont;
}
form {
max-width: 300px;
min-width: 250px;
padding: 20px 50px;
border: 2px solid gray;
border-radius: 10px;
font-family: coolfont;
background-color: #fff;
}
#moveupwards {
margin-top: -20px;
}
p {
margin-top: 30px;
}
h2 {
background-color: #FEFFED;
padding: 20px 35px;
margin: -10px -50px;
text-align: center;
border-radius: 10px 10px 0 0;
font-family: info;
}
hr {
margin: 10px -50px;
border: 0;
border-top: 1px solid #ccc;
}
input[type=text] {
width: 82%;
padding: 10px;
margin-top: 30px;
border: 1px solid #ccc;
padding-right: 40px;
font-size: 16px;
font-family: coolfont;
}
input[type=email] {
width: 82%;
padding: 10px;
margin-top: 30px;
border: 1px solid #ccc;
padding-right: 40px;
font-size: 16px;
font-family: coolfont;
}
textarea {
width: 82%;
height: 95px;
padding: 10px;
resize: none;
margin-top: 30px;
border: 1px solid #ccc;
padding-right: 40px;
font-size: 16px;
font-family: coolfont;
margin-bottom: 30px;
}
#submit {
text-decoration: none;
width: 100%;
text-align: center;
display: block;
background-color: #FFBC00;
color: #fff;
border: 1px solid #FFCB00;
padding: 10px 0;
font-size: 20px;
cursor: pointer;
border-radius: 5px;
}
#media only screen and (max-width: 457px) {
form {
max-width: 200px;
min-width: 150px;
padding: 10px 50px;
margin-left: 50px;
}
input[type=text] {
padding-right: 30px;
}
textarea {
padding-right: 30px;
}
}
#media only screen and (max-width: 365px) {
form {
max-width: 140px;
min-width: 90px;
padding: 10px 50px;
margin-left: 80px;
}
input[type=text] {
padding-right: 10px;
}
textarea {
padding-right: 10px;
}
}
<a class="button" id="popup" onclick="div_show1()">ORDER NOW</a>
<a class="button" id="popup" onclick="div_show2()">ORDER NOW</a>
<a class="button" id="popup" onclick="div_show3()">ORDER NOW</a>
<div id="abc">
<!-- Popup Div Starts Here -->
<div id="popupContact">
<!-- Contact Us Form -->
<form action="form.php" id="form" method="post" name="form" enctype="multipart/form-data">
<img id="close" src="images/redcross.png" width="50" onclick="div_hide()">
<h2 id="ordertype" name="ordertype" type="text">#</h2>
<hr>
<div id="moveupwards">
<input id="name" name="name" required="required" placeholder="Name" type="text">
<input id="email" name="email" required="required" placeholder="Email" type="email">
<textarea id="message" name="message" placeholder="Comments/Questions"></textarea>
<input id="submit" name="submit" class="submit" type="submit" value="Order">
</div>
</form>
</div>
<!-- Popup Div Ends Here -->
</div>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: -';
$to = 'example#gmail.com';
$subject = $_GET['ordertype'];
$body = "From: ".$name.
"\r\n E-Mail: ".$email.
"\r\n Message: \r\n".$message;
if ($_POST['submit']) {
if (mail($to, $subject, $body, $from)) {
echo '<script>
alert("Order has been placed. We will be in touch with you shortly."); location.href="#";
</script>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
As mentioned by #chris85, <h2> elements are not posted when submitting a form.
You may want to check out the HTML forms guide # MDN.
I suggest populating a hidden <input> with the content of the <h2>.
Something like this demonstration:
function set_value() {
var title = document.getElementById("ordertitle"),
type = document.getElementById("ordertype");
title.innerHTML = type.value = "$400 Website Order";
}
function show_hidden() {
// for demonstration purposes
var type = document.getElementById("ordertype");
type.type="text";
}
document.getElementById("set_value").addEventListener('click',set_value);
document.getElementById("show_hidden").addEventListener('click',show_hidden);
<form action="form.php" method="post" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="ordertype" id="ordertype" />
<h2 id="ordertitle"></h2>
<button id="set_value" >Set Value</button>
<button id="show_hidden">Show Hidden Input</button>
</form>
Also, since you've set your form to method="post", you'll want to retrieve the value from the $_POST array rather than $_GET:
$subject = $_POST['ordertype'];
For reference, see The Post Method.

Categories