I don't know if the problem is with my form or my javascript but the validation isn't working and I'm not getting any errors in the console. Can anyone check and see the form is working or the problem is with the javascript
const formSection = document.getElementById('davididhere');
const mailInput = document.getElementById('email');
const messageError = document.getElementById('error-messages');
formSection.addEventListener('submit', (e) => {
if (mailInput.value === mailInput.value.toLowerCase()) {
messageError.textContent = '';
} else {
e.preventDefault();
messageError.textContent = '*email must be in lower case <br> * form not sent';
}
})
<section id="contactpage" class="form-section">
<div class="form-container">
<form action="https://formspree.io/f/myyvzkag" method="post" id="davididhere">
<ul class="form-info">
<li>
<input type="text" maxlength="30" name="user_name" class="name-text-box" id="full-name" placeholder="Full Name" required="" />
</li>
<li>
<input type="email" name="user_email" class="name-last-text-box" id="email" placeholder="Email Address" required="" />
</li>
<li>
<textarea id="text-box" name="message" maxlength="500" class="enter-form" cols="30" rows="10" placeholder="Enter text here" required=""></textarea>
</li>
</ul>
<input type="submit" value="Get in touch" class="send-btn" />
<small id="error-messages"></small>
</form>
my css
#media screen and (min-width: 768px) {
.greet {
background: url(desktop2.svg) no-repeat 100% 0%;
}
.grid-containers {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.picture-box {
background: url(planeleft.svg) no-repeat 0% 20%,
url(planeright.svg) no-repeat 100% 100%;
}
.send-btn {
display: none;
}
the .send-btn is the problem when it doesn't display in the desktop version it stops working with my function. So I need to figure out how to use media queries to work both breakpoints.
Code snipped is working here. Now the question is do you expect some kind of an error in the console since you stated that you are not receiving anything there. You can throw an error in addition to already defined textContent.
const formSection = document.getElementById('davididhere');
const mailInput = document.getElementById('email');
const messageError = document.getElementById('error-messages');
formSection.addEventListener('submit', (e) => {
if (mailInput.value === mailInput.value.toLowerCase()) {
messageError.textContent = '';
} else {
e.preventDefault();
messageError.textContent = '*email must be in lower case <br> * form not sent';
throw new Error('Email must be in lower case!');
}
})
Related
I literally started coding two days ago. I'm working on a project for a job application in which I have to create a form that goes green and red depending on success/error, and I used a YouTube tutorial to guide me through. Everything was going fine until I tried to code the error and success classes (i.e. the fields turning red or green) for the inputs, and after clicking submit nothing happens!
Here is the code I have written so far. Where have I gone wrong?
HTML:
<div class="container">
<form class="form" id="form"; action="mailto:changed#email.com"
method="POST"
enctype="text/plain:
name="EmailForm>
<div class="form-control">
<label>Name</label>
<input type="text" name="Name" placeholder="Enter Your Name" id="name">
</div>
<div class="form-control">
<label>Email</label>
<input type="email" name="Email" placeholder="Enter Your Email" id="email">
</div>
<div class="form-control">
<label>Card</label>
<input type="tel" inputmode="numeric" pattern="[0-9\s]{13,19}"
autocomplete="cc-number" maxlength="19"
placeholder="Enter A Proxy Credit Card Number" id="ccn">
</div>
<button type="submit"; style="background-color:#e70064;
border-color:#3c3c3b; color:#3c3c3b">Submit</button>
</form>
</div>
CSS:
* {
box-sizing: border-box;
}
body {
background-color:fff;
display:flex;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
}
.container {
background-color:#89c82e;
border: 5px solid #3c3c3b;
border-radius:20px;
margin-top:15px;
margin-bottom:15px;
width:300px;
max-width:100%;
}
.form{
padding: 30px 40px;
font-family:"calibri"
}
.form-control.success input {
border-color: #2ecc71;
}
.form-control.error input {
border-color:#e74c3c
}
JS:
const form = document.getElementById('form');
const name = document.getElementById('name');
const email = document.getElementById('email');
const ccn = document.getElementById('ccn');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// get the values from the inputs
const nameValue = name.value.trim();
const emailValue = email.value.trim();
const ccnValue = ccn.value.trim();
if(nameValue === "") {
// show error
// add error class
setErrorFor(name)
} else {
// add success class
setSuccessFor(name)
}
}
function setErrorFor(input) {
const formControl = input.parentElement; // .form-control
// add error class
formControl.classname = 'form-control error'
}
thanks so much!
By doing
.form-control.error input {
border-color:#e74c3c
}
You are setting any divs with a class name of form-control error that has an input inside to have a border color of red. But by default divs don't have a visible border. If you want the input field to turn red or green based on success/failure, set the inputs to have a border-color. You have the inputs already at the top of the js file, you can use those.
Also, in the setErrorFor function, it is .className, not .classname.
<div class="control">
<input
type="email"
id="email"
class="email-address"
onblur="getValEmail()"
/>
<label for="email">Email</label>
</div>
<div class="control box">
<textarea id="message" onblur="getValMsg()"></textarea>
<label for="message">message</label>
</div>
function getValEmail() {
const valEmail = document.getElementById("email");
valEmail.addEventListener("blur", function () {
if (valEmail.value) valEmail.parentElement.classList.add("filled");
else valEmail.parentElement.classList.remove("filled");
});
}
function getValMsg() {
const valMsg = document.getElementById("message");
valMsg.addEventListener("blur", function () {
if (valMsg.value) valMsg.parentElement.classList.add("filled");
else valMsg.parentElement.classList.remove("filled");
});
}
.filled label,
input:focus + label,
textarea:focus + label {
top: 0;
font-size: 1.2rem;
}
These are HTML, Javascript and CSS codes in order.
What I'm trying to achieve here is that once user writes email address/message, labels that are inside of input/textarea go up. So, when input/textarea are filled up, labels should disappear to the top. It does its job but not responsively. "filled" class is added after a couple of more clicks happen, which means that labels only go up to the top after I click the box again.
Result looks like this.
This is only achieved after a few more clicks in the box.
You don't need js here at all. The :placeholder-shown pseudo-class will do what you actually need to achieve (note the non-empty placeholder attrs required for chrome):
.control {
position: relative;
margin-top: 20px;
}
input+label,
textarea+label {
position: absolute;
left: 0;
top: 0;
transition: 300ms;
}
input:focus+label,
input:not(:placeholder-shown)+label,
textarea:focus+label,
textarea:not(:placeholder-shown)+label {
top: -20px;
}
<div class="control">
<input type="email" id="email" class="email-address" placeholder=" " />
<label for="email">Email</label>
</div>
<div class="control box">
<textarea id="message" placeholder=" "></textarea>
<label for="message">message</label>
</div>
Here's a codepen.
In your css use:
transform:translateY(-2em)
change accordingly to your adjustment.
Im having issues with getting addEventListener to close a form that I opened using addEventListener.
For example, here is my HTML, CSS and JS for opening the form:
let addAlarmLink = document.getElementById('alarm-add');
let addAlarmForm = document.getElementById('adding-alarm');
addAlarmLink.addEventListener('click', () => {
if (addAlarmForm.style.display === 'none' || addFriendForm.style.display === 'none') {
addAlarmForm.style.display = 'block';
} else {
addAlarmForm.style.display = 'none';
}
});
#adding-alarm {
display: none;
z-index: 1;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
width: 25vw;
}
<section id="adding-alarm" style="display: none;">
<form id="alarm-form">
<h5 id="close">X</h5>
<h4>Adding Alarm</h4>
<input class="add-form-info" id="n-name" placeholder="Nickname" type="text" >
<input class="add-form-info" id="f-name" placeholder="First Name" type="text" >
<input class="add-form-info" id="l-name" placeholder="Last Name" type="text" >
<h4>Login Info </h4>
<input class="add-form-info" id="add-username-email" placeholder="Username or Email of Friend" type="text" >
<input class="login-info" id="add-alarm-submit" type="submit" value="Add Alarm">
</form>
</section>
This works fine, the form opens and is editable. However, when setting up a addEventListener to close the form, its not triggering or even being recognized. Here's the code for that:
let closeForm = document.getElementById('close');
closeForm.addEventListener('click', () => {
addAlarmForm.display.style = 'none';
});
This did not work and i tried it a few other ways by using onClick and setting up a function but had the same results. I also tried setting up a console.log to just spit out a message and i get nothing in the console. One other thing i noticed is that style gets pushed out of #adding-alarm to element.style when inspecting the styles.
picture of style showing under element.style rather than updating #adding-alarm
Is there something im doing wrong or a better to make this happen?
This is all very new to me.
It is working fine taken from your code only . Here is a working example in snippet below ,the only problem was told in the other answer that is .style.display is wrongly written as .display.style .
let addAlarmLink = document.getElementById('alarm-add');
let addAlarmForm = document.getElementById('adding-alarm');
addAlarmLink.addEventListener('click', () => {
if (addAlarmForm.style.display === 'none' || addFriendForm.style.display === 'none') {
addAlarmForm.style.display = 'block';
} else {
addAlarmForm.style.display = 'none';
}
});
let closeForm = document.getElementById('close');
closeForm.addEventListener('click', () => {
addAlarmForm.style.display = 'none';
});
#adding-alarm {
display: none;
z-index: 1;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
width: 25vw;
}
<div class="add-option"> <p>Add an alarm to be reminded to do a task.</p> <i id="alarm-add" class="fas fa-plus-circle">+</i> </div>
<section id="adding-alarm" style="display: none;">
<form id="alarm-form">
<h5 id="close">X</h5>
<h4>Adding Alarm</h4>
<input class="add-form-info" id="n-name" placeholder="Nickname" type="text" >
<input class="add-form-info" id="f-name" placeholder="First Name" type="text" >
<input class="add-form-info" id="l-name" placeholder="Last Name" type="text" >
<h4>Login Info </h4>
<input class="add-form-info" id="add-username-email" placeholder="Username or Email of Friend" type="text" >
<input class="login-info" id="add-alarm-submit" type="submit" value="Add Alarm">
</form>
</section>
Notice mixed up order of properties. In working case you have:
addAlarmForm.style.display = 'block';
And in not working case you have:
addAlarmForm.display.style = 'none';
This is likely to be your error. However, you said nothing is showing on the console, and it's suspicious because clearly there should be some error on the console (display is not defined on HTMLElement)
Your code is actually running fine. it only need some clean up and few adjustment,
here is some adjustment I made to your code and it works as expected.
let addAlarmLink = document.getElementById('showForm');
let closeForm = document.getElementById("closeForm");
let addAlarmForm = document.getElementById('adding-alarm');
let addAlarmSubmit = document.getElementById("add-alarm-submit");
addAlarmLink.addEventListener('click', () => {
if (addAlarmForm.style.display === 'none') {
addAlarmForm.style.display = 'block';
addAlarmLink.style.display = 'none';
closeForm.style.display = 'block';
} else {
addAlarmForm.style.display = 'none';
}
});
if(closeForm.addEventListener("click", () => {
addAlarmForm.style.display = 'none';
closeForm.style.display = 'none';
addAlarmLink.style.display = 'block';
}));
if(addAlarmForm.addEventListener('click', (event) => {
event.preventDefault();
alert('form submitted successfully..!')
}));
#adding-alarm {
z-index: 1;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
width: 25vw;
}
<button id="showForm">show form</button>
<button id="closeForm" style="display: none;">Close form</button>
<section id="adding-alarm" style="display: none;">
<form id="alarm-form">
<h4>Adding Alarm</h4>
<input class="add-form-info" id="n-name" placeholder="Nickname" type="text" >
<input class="add-form-info" id="f-name" placeholder="First Name" type="text" >
<input class="add-form-info" id="l-name" placeholder="Last Name" type="text" >
<h4>Login Info </h4>
<input class="add-form-info" id="add-username-email" placeholder="Username or Email of Friend" type="text" >
<input class="login-info" id="add-alarm-submit" type="submit" value="Add Alarm">
</form>
</section>
can anyone help me to add this icon <i class="fas fa-check-circle"></i> if the background color changes to green using the following code:
document.querySelectorAll('input').forEach((inp) => {
inp.addEventListener('focusout', () => {
let value = inp.value.split(' ').join('')
if (value == '') {
inp.style.backgroundColor = "red";
} else {
inp.style.backgroundColor = "green";
let icon = document.createElement('i')
icon.classList.add('fas', 'fa-check-circle')
inp.appendChild(icon)
}
})
})
HTML Code
<section class="control-group">
<label class="control-label" for="company">Company</label>
<div class="controls">
<input
autofocus=""
class="input-xlarge"
id="company"
name="company"
placeholder="Company name"
type="text"
value=""
/>
</div>
</section>
<section class="control-group">
<label class="control-label" for="fname">Name</label>
<div class="controls two-col">
<input
class="input-medium"
id="fname"
name="fname"
placeholder="First name"
type="text"
value=""
/>
</div>
the excepted result is that the icon should be nest to every text field that has been filled.
You are trying tp append a child to an input. An input does not have children. You need to add it after the input. Also with your code, it would add a bunch of elements every time it loses focus.
document.querySelectorAll('input').forEach((inp) => {
let icon = document.createElement('i')
icon.classList.add('fas', 'fa-check-circle', 'hidden')
inp.after(icon);
inp.addEventListener('focusout', () => {
let value = inp.value.split(' ').join('')
if (value == '') {
inp.style.backgroundColor = "red";
icon.classList.add('hidden');
} else {
icon.style.display = 'inilne-block';
inp.style.backgroundColor = "green";
icon.classList.remove('hidden');
}
})
})
input {
padding-right: 20px;
}
input + i {
position: absolute;
margin-left: -20px;
}
i.hidden {
display: none;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<input type="text"><input type="text"><input type="text">
You cannot add children to an input element. However, you can add the icon next to the input by means of insertAdjacentHTML().
document.querySelectorAll('input').forEach((inp) => {
inp.addEventListener('focusout', () => {
let value = inp.value.split(' ').join('')
if (value == '') {
inp.style.backgroundColor = "red";
} else {
inp.style.backgroundColor = "green";
inp.insertAdjacentHTML('afterend', '<i class="fas fa-check-circle">Your icon here</i>');
}
})
})
<input type="text">
If you want the icon "inside" the input, then you need to use CSS to set it as a background image, which is not related to "adding a HTML element using JavaScript".
I would suggest that rather than adding new elements in response to user input, you build all the elements into your html, and then hide/show/style them appropriately with a css class or two:
document.querySelectorAll('input').forEach((inp) => {
inp.addEventListener('focusout', () => {
const parent = inp.parentNode;
let value = inp.value.split(' ').join('');
if (value == '') {
parent.classList.remove("valid");
parent.classList.add("invalid");
} else {
parent.classList.remove("invalid");
parent.classList.add("valid");
}
});
});
.controls i {
display: none;
}
.controls.valid input {
background-color: green;
}
.controls.valid i {
display: inline;
}
.controls.invalid input {
background-color: red;
}
<section class="control-group">
<label class="control-label" for="company">Company</label>
<div class="controls">
<input
autofocus=""
class="input-xlarge"
id="company"
name="company"
placeholder="Company name"
type="text"
value=""
/>
<i class="fas fa-check-circle">test</i>
</div>
</section>
<section class="control-group">
<label class="control-label" for="fname">Name</label>
<div class="controls two-col">
<input
class="input-medium"
id="fname"
name="fname"
placeholder="First name"
type="text"
value=""
/>
<i class="fas fa-check-circle">test</i>
</div>
</section>
elem = document.createElement("<div id='myID'> my Text </div>");
I have used pure JavaScript to validate this login form consider the below example and also check out the live demo here https://codepen.io/uicreation/pen/xpdbKe
hope it will be help you to understand how JavaScript validation is works.
Live Demo
if(document.getElementsByClassName('firstForm')[0]){
document.getElementsByClassName('firstForm')[0].onsubmit = function(e){
e.preventDefault();
var field = this;
var email = field.querySelector('input[type=email]');
var pass = field.querySelector('input[type=password]');
var regex = /^(([^<>()[\]\\.,;:\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,}))$/;
if(!regex.test(email.value)){
console.log("enter a valid email address")
} else if(pass.value.length < 8){
console.log("password should be greater than 8 characters")
} else {
console.log("success!")
}
}
}
form {
margin: 30px 0 0 30px;
}
fieldset {
padding:5px;
}
label {
min-width:60px;
display: inline-block;
}
input[type=submit]{
margin-top:5px;
margin-left:5px;
}
<form class="firstForm" novalidate>
<fieldset>
<label>Email</label>
<input type="email" name="email" placeholder="Enter Email" />
</fieldset>
<fieldset>
<label>Password</label>
<input type="password" name="password" placeholder="Enter Password" />
</fieldset>
<input type="submit" value="Login" />
</form>