I want to show the error message of required if mandatory fields are left blank. I implement it using the following way but every time the function checkinput() is invoked it adds a new span element due to which "required" message is outputted multiple times. I want the span element to be added once and disappears when user fills in the requirement. Here is my code.
const checkinput=(event)=>{
if(event.target.value===""){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
Reason why new span element is added each time you have a empty input field is because you are calling insertAdjacentHTML each time and inserting a new span element.
What you should do is add span elements with each input field in the html and initially they should be empty.When you want to validate the input fields, if any of the input is empty, select the span element next to that input element and show the error message in that span element using .textContent property. To clear the error message, you just need to set .textContent of the span element to an empty string.
Following code snippets show different ways of validating form inputs.
Form validation on form submit
Following code snippet validates form inputs when form is submitted.
const form = document.querySelector('form');
const usernameError = document.querySelector('#usernameError');
const passwordError = document.querySelector('#passwordError');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username', usernameError);
const passwordValid = validateField(form, 'password', passwordError);
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
function validateField(form, fieldName, errorEl) {
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
<button>Submit</button>
</form>
Form validation on input focus loose
Following code snippet validates form inputs when any of the input looses focus.
const form = document.querySelector('form');
const inputsContainer = document.getElementById('formInputsContainer');
const submitBtn = document.querySelector('button');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username');
const passwordValid = validateField(form, 'password');
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
submitBtn.addEventListener('focus', () => {
form.requestSubmit();
});
inputsContainer.addEventListener('focusout', (event) => {
validateField(form, event.target.name);
});
function validateField(form, fieldName) {
const errorEl = document.getElementById(`${fieldName}Error`);
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div id="formInputsContainer">
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
</div>
<button>Submit</button>
</form>
Form validation as user types in the input field
Following code snippet validates form input as user types in any input field.
const form = document.querySelector('form');
const inputsContainer = document.getElementById('formInputsContainer');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username');
const passwordValid = validateField(form, 'password');
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
inputsContainer.addEventListener('input', (event) => {
validateField(form, event.target.name);
});
function validateField(form, fieldName) {
const errorEl = document.getElementById(`${fieldName}Error`);
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div id="formInputsContainer">
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
</div>
<button>Submit</button>
</form>
You need something like
if(event.target.value==="" && document.querySelector('span') === null){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
You only want to add a span IF the value is an empty string AND the span hsan't been added yet.
You can use this code which create a span which is add to the DOM with the ID which is based on the form element'sname attribute. And that element can be refered to based on the ID which was attach to it before It's been add to the DOM
const checkinput=(event)=>{
if(event.target.value===""){
let spanId = `input-${event.target.name}`
let span = `<span id="${spanId}" class="text-danger">Required</span>`
setTimeout(() =>{
document.getElementById(spanId).remove();
}, 5000);
event.target.insertAdjacentHTML('afterend',span)
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
<form>
<input type="text" name="username" id="username"/>
<input type="text" name="password" id="password"/>
<input type="text" name="confirmPassword" id="confirmPassword"/>
</form>
May it help
<style>
.errorMsg {
border: 1px solid red;
}
.err {
color: red;
}
</style>
<form>
<input type="text" name="name" id="name">
<input type="password" name="password" id="password">
<button id="submit" type="submit">Submit</button>
</form>
<script>
let nameTag = document.querySelector('#name');
let passwordTag = document.querySelector('#password');
let submitBtn = document.querySelector('#submit');
nameTag.addEventListener('blur', e => validation(e));
passwordTag.addEventListener('blur', e => validation(e));
function validation(e) {
if (e.target.value == '') {
e.target.classList.add('errorMsg')
submitBtn.setAttribute('disabled', true) // Disable submit that user cannot submit
e.target.insertAdjacentHTML('afterend', `<span class="err ${e.target.id}">It is required</span>`)
// In the above line we are inserting an element with class same as id of input that in the remove we remove a particular error message only
} else {
e.target.classList.remove('errorMsg')
submitBtn.removeAttribute('disabled')
document.querySelector(`.err.${e.target.id}`).remove();
//Here code is saying that the element with if 'err' and 'class same as id of input' if both class present then remove it
}
}
</script>
Adding the class = id that a special error message delete
Related
I wrote the code below and I'm trying to change the input field background color the moment I type something. I have 4 input fields. If I click submit in the first time and any field is empty, the color of this field will change to red, but I need to change the color to green the moment I fill this empty field.
const submitButton = document.getElementById("submit")
const inputField = document.querySelectorAll(".input")
let requiredField = document.querySelectorAll(".requiredField")
inputField.forEach(function (item){
submitButton.addEventListener("click", function (){
if(item.value == '') {
item.classList.add("red");
item.nextElementSibling.classList.add("red");
}
else{
item.classList.add("green")
item.nextElementSibling.classList.remove("green");
}
})
})
Try this:
inputField.forEach(field => {
field.addEventListener("input", () => {
field.classList.add("green");
});
});
If you want only one field to be green at a time:
inputField.forEach(field => {
field.addEventListener("input", () => {
inputField.forEach(input => {
input.classList.remove("green");
});
field.classList.add("green");
});
});
I'm not sure all your code does what you are expecting, but I have an approach that is approaching your requirement by listening to the keyup event and evaluating if the input has content or not; you should be able to reconfigure this to your use case.
I also moved your loop of the four loops inside the submit button click handler-- otherwise you are adding three identical handlers to the button.
const submitButton = document.getElementById("submit")
const inputField = document.querySelectorAll(".input")
submitButton.addEventListener("click", function(e) {
inputField.forEach(function(item) {
e.preventDefault();
if (item.value == '') {
item.classList.add("red");
item.nextElementSibling.classList.add("red");
} else {
item.classList.add("green")
item.nextElementSibling.classList.remove("green");
}
})
})
inputField.forEach(function (item) {
item.addEventListener('keyup', function(e) {
const theInput = e.target;
if (theInput.value) {
theInput.classList.remove('red');
theInput.classList.add('green');
}
});
});
.red {
border: red 2px solid;
}
.green {
border: green 2px solid;
}
<label for="myfield">My Field:</label>
<input class="input" id="myfield" name="myfield" />
<br/>
<label for="myotherfield">My Other Field:</label>
<input class="input" id="myotherfield" name="myotherfield" />
<button id="submit">Submit</button>
Note another option would be to omit the JavaScript altogether and just go for native validation-- you have less control about when and how the validation styles are applied, but also less JS to write:
const submitButton = document.getElementById("submit")
submitButton.addEventListener("click", function(e) {
e.preventDefault();
});
.input:invalid {
border: red 2px solid;
}
.input:valid {
border: green 2px solid;
}
<label for="myfield">My Field:</label>
<input class="input" id="myfield" name="myfield" required/>
<br/>
<label for="myotherfield">My Other Field:</label>
<input class="input" id="myotherfield" name="myotherfield" required />
<button id="submit">Submit</button>
If you go with the first approach, make sure you are providing adequate feedback for screen readers and assistive technologies to understand the form's state-- if there are no validation or validation-state attributes on the input and you are only indicating validity with a green/red border, screen readers won't be aware of it. Furthermore, those with red/green color blindness might not be able to perceive the difference.
You don't actually need any JavaScript for this. Add the required attribute on the inputs and then style them accordingly with css.
<input type="text" required>
<input type="text" required>
<input type="text" required>
<input type="text" required>
input:valid {
background-color: green;
}
input:invalid:required {
background-color: red;
}
try this for a quick fix:
const submitButton = document.getElementById("submit")
const inputField = document.querySelectorAll(".input")
inputField.forEach(field => {
field.addEventListener("input", () => {
inputField.forEach(input => {
input.classList.remove("green");
input.classList.remove("red");
});
if (field.value !== "") {
field.classList.add("green");
} else {
field.classList.add("red");
}
});
});
Goodmorning everyone,
I have a problem with a script for validating a form.
Given that the module has server-side validation in PHP, what I want to achieve, too, is client-side validation.
This validation is very simple.
When you click on the SUBMIT button, you must check if all the mandatory fields have been filled in.
If they are not:
must add a class to the input to make it change color;
must change the content of the icon next to the input field.
I use this script which works with regards to check and class on input. However, it uses a check on the NAME of the fields.
HTML
<form id="signinform" method="post" action="" class="wp-user-form" autocomplete="off" onsubmit="event.preventDefault(); validateMyForm();" novalidate>
<div class="msc-login-form-input">
<input type="text" name="log" value="" size="20" id="user_login" placeholder="Username o Email" autocomplete="off" required onkeyup="validateElement(this)"/>
<span id="errorsign"></span> </div>
<div class="msc-login-form-input">
<input type="password" name="pwd" value="" size="20" id="user_pass" placeholder="Password" autocomplete="off" required onkeyup="validateElement(this)"/>
<span id="errorsign"></span> </div>
<div class="msc-login-form-input-sendh">
<input type="submit" id="submit-login" name="submit-login" value="" class="user-submit" />
</div>
</form>
JS
<script lang="javascript">
function validateMyForm(){
let isFormValid = true;
let elems = document.getElementsByName("namefield");
for(let i=0; i< elems.length; i++)
{
let elem = elems[i];
if(elem.value.length < 1)
{
if(isFormValid){
isFormValid = false;
}
}
validateElement(elem);
}
if(isFormValid)
{
document.getElementById("signinform").submit();
return true;
}
}
function validateElement(elem){
if(elem.value.length < 1)
{
elem.className = "errorClass";
}else{
elem.className = "okClass";
}
}
</script>
CSS
<style>
.msc-login-form-input input.okClass {
background-color: #ffffff;
color: #3F4254;
}
.msc-login-form-input input.errorClass {
background-color: #4d40ff;
color: #ffffff;
}
.msc-login-form-input #errorsign {
width: 35px;
background-color: rgba(0,0,0,0.05);
min-height: 100%;
align-items: center;
justify-content: center;
text-align: center;
display: flex;
}
.msc-login-form-input #errorsign::before {
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f100";
}
.msc-login-form-input #errorsign.fail::before {
content: "\f00d";
color:#4d40ff;
}
.msc-login-form-input #errorsign.okay::before {
content: "\f00c";
color:#FF1493;
}
</style>
The problem is that the NAMEs of my fields are not the same and therefore that loop cannot work.
How can I solve without duplicating the loop for each form field?
How can I also add the control on the class of the icon next to it?
Thank you.
If you don't want to use the builtin validation, I'd do it as follows
let formvalid = true;
//these are the divs surrounding your elements to be validated
let elements = document.getElementsByClassName("msc-login-form-input")
for (let i = 0; i < elements.length; i++) {
//this is the input to be validated
let input = elements[i].getElementsByTagName("input")[0];
//this is the span element holding the icon
let icon = elements[i].getElementsByTagName("span")[0];
let valid = validateElement(input);
//set the classes input and span according to the validation result
input.classList.Add(valid ? "okClass" :"errorClass");
span.classList.Add(valid ? "okay" :"fail");
input.classList.Remove(valid ? "errorClass": "okClass");
span.classList.Remove(valid ? "fail" : "okay" );
//the form is only valid if ALL elements are valid
formvalid &= valid;
}
function validateElement(element) {
if (input.value.length === 0) return false;
//any other validations you want to do
return true;
}
Furhtermore you have a problem in your DOM tree. You have mutliple <span> elements with the same id="errorsign". That's not gonna work, because an id has to be unique. So remove the ids and grab the <spans> from their parents as shown above.
You could also just add the "okay" and "fail" to the surrounding <div> and adapt your css accordingly. Ie something like the following CSS
.msc-login-form-input.okay input {
...
}
.msc-login-form-input.fail input {
...
}
.msc-login-form-input.okay span::before {
...
}
.msc-login-form-input.fail span::before {
...
}
And the following JS
let formvalid = true;
//these are the divs surrounding your elements to be validated
let elements = document.getElementsByClassName("msc-login-form-input")
for (let i = 0; i < elements.length; i++) {
//this is the input to be validated
let input = elements[i].getElementsByTagName("input")[0];
let valid = validateElement(input);
element.classList.Add(valid ? "okay" : "fail");
element.classList.Remove(valid ? "fail": "okay");
formvalid &= valid;
}
I want to check if all my inputs are filled to activate a submit button, but with my code it checks only one input.
My HTML (with TWIG) :
<div class="content-wrapper content-wrapper--close">
<form class="form form--width">
<fieldset class="form__fieldset input">
<input class="input__field" id="name" name="name"/>
<label class="input__label" for="name">Nom et prénom</label>
</fieldset>
<fieldset class="form__fieldset input">
<input class="input__field" id="structure" name="structure"/>
<label class="input__label" for="structure">Structure</label>
</fieldset>
<fieldset class="form__fieldset input">
<input class="input__field" id="email" name="email"/>
<label class="input__label" for="email">Adresse email</label>
</fieldset>
<fieldset class="form__fieldset input">
<textarea class="input__field input__field--textarea" name="message" id="message" rows="10">
</textarea>
<label class="input__label" for="message">Message</label>
</fieldset>
<fieldset class="form__fieldset">
<div class="cta is-disabled">
<input type="submit" class="cta__link button" value="Envoyer">
</div>
</fieldset>
</form>
</div>
My javascript:
/**
* Add event listener on input.
*
* #param form
*/
addListener(form) {
const inputs = form.querySelectorAll('.input__field');
[...inputs].map( input => {
input.addEventListener('focus', (event) => {
event.target.classList.add('is-fill');
});
input.addEventListener('blur', (event) => {
if (event.target.value === '') {
event.target.classList.remove('is-fill');
}
});
});
}
// // If all fields are filled, remove class 'is-disabled'
handleInputs(items) {
const inputs = items.querySelectorAll('.input__field');
const submitButton = document.querySelector('.form .cta');
[...inputs].map( input => {
input.addEventListener('input', (e) => {
if(e.target.value !== '') {
submitButton.classList.remove('is-disabled');
} else {
if(!submitButton.classList.contains('is-disabled')) {
submitButton.classList.add('is-disabled');
}
}
});
});
}
For now it only works with only one input and I don't know how to do to check all the input. If somebody can help me, I don't find any answer.
Thanks
With HTML5 you can style the form button when the form is not invalid. Simple CSS rule and it will apply the styles. It also by default prevents the form from submitting.
The button will remain red until the form is filled in with a valid name, email, and date. I also added a rule that alters the current element being edited which your code is also doing.
input {
margin: .5rem;
}
input:focus {
box-shadow: 0px 0px 5px 5px #0ff;
}
form:invalid input[type="submit"] {
background-color: red
}
<form>
<fieldset>
<legend>User:</legend>
<label for="name">Name:</label>
<input type="text" id="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" required><br>
<label for="dob">Date of birth:</label>
<input type="date" id="bod" required>
</fieldset>
<input type="submit" />
</form>
You might need to loop through each input every time an input changes:
$(document).ready(function () {
var shouldShowSubmitBtn = true;
$("input").change(function () {
$(":input").each(function () {
if ($(this).val() == '') {
shouldShowSubmitBtn = false;
return false;
}
});
});
});
The code I used :
for (const input of inputs) {
input.addEventListener(`input`, () => {
for (const input of inputs) {
if (input.value.length === 0) {
submitButton.disabled = true;
cta.classList.add('is-disabled');
break;
} else {
submitButton.disabled = false;
cta.classList.remove('is-disabled');
}
}
});
}
I am trying to change the display property of some text using JS, upon button click.
I have confirmed that the function is firing and running correctly using debugger, but for some reason, I can't grab the specific element I need to change, and assign it to a variable. I also have jquery set up on the page.
I have tried using the console, and document.getElementById('warning-textID') returns the correct element, but when I try to set it to a variable in console, it returns undefined. Am I missing something super obvious here?
Here is the HTML, function and css.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
});
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if(enteredValue == validParam){
console.log('do the thing')
if(cookieCreated == false && enteredValue == validParam){
warning.innerText = "Please enable cookies";
warning.style.display = "";
return;
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "";
enteredValue.value = "";
return;
}
}
.warning-text {
color: red; text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper" >
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
I fixed some mistakes and it worked.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if (enteredValue === validParam) {
console.log('do the thing')
if (cookieCreated == false && enteredValue === validParam) {
warning.innerText = "Please enable cookies";
warning.style.display = "block";
return;
}
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "block";
enteredValue.value = "";
return;
}
}
});
.warning-text {
color: red;
text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper">
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
I'm trying to show an error message in the span tags using jQuery. I can get the form fields to highlight in a red box and green box if input right but the text wont show up. I'm new to coding and been looking on the web for ideas and fixes, I know I'm missing something and it maybe simple but I'm racking my brains on it.
$(document).ready(function() {
// Name can't be blank
$('#name').on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// Email must be an email
$('#email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// Message can't be blank
$('#message').keyup(function(event) {
var input = $(this);
var message = $(this).val();
console.log(message);
if (message) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// After Form Submitted Validation
$("#contact_submit button").click(function(event) {
var form_data = $("#contact").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_submit" + form_data[input]['name'], ['email'], ['message']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
}
else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
event.preventDefault();
}
else {
alert('No errors: Form will be submitted');
}
});
});
.error {
display: none;
margin-left: 10px;
}
.error_show {
color: red;
margin-left: 10px;
}
input.invalid,
textarea.invalid {
border: 2px solid red;
}
input.valid,
textarea.valid {
border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="body">
<form id="contact" method="post" enctype="multipart/form-data" action="">
<h1 class="title">Contact</h1>
<div>
<label for="name">Your Fullname</label>
<input type="text" id="name" name="name" required placeholder="Your Name">
<span class="error error_show">This field is required</span>
</div>
<div>
<label for="email">Your Full Email</label>
<input name="email" type="email" id="email" required placeholder="Your Email">
<span class="error error_show">This field is required</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<span class="error error_show">This field is required</span>
</div>
<div id="contact_submit">
<button type="submit"></button>
</div>
</form>
</section>
I think you might have made it more complicated than it needed to be. See if the below snippet doesn't work the way you expected.
$(document).ready(function() {
$('#name').on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#message').keyup(function(event) {
var input = $(this);
var message = $(this).val();
console.log(message);
if (message) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$("#contact_submit #submit_button").click(function(event) {
$("#name_error").hide();
$("#email_error").hide();
$("#message_error").hide();
var success = true;
if (!$("#name").hasClass("valid")) {
success = false;
$("#name_error").show();
}
if (!$("#email").hasClass("valid")) {
success = false;
$("#email_error").show();
}
if (!$("#message").hasClass("valid")) {
success = false;
$("#message_error").show();
}
if (success === false) {
event.preventDefault();
}
else {
alert('No errors: Form will be submitted');
}
});
});
.error {
display: none;
margin-left: 10px;
}
.error_show {
color: red;
margin-left: 10px;
display: none;
}
input.invalid,
textarea.invalid {
border: 2px solid red;
}
input.valid,
textarea.valid {
border: 2px solid green;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<section class="body">
<form id="contact" method="post" enctype="multipart/form-data" action="">
<h1 class="title">Contact</h1>
<div>
<label for="name">Your Fullname</label>
<input type="text" id="name" name="name" required placeholder="Your Name">
<span id="name_error" class="error_show">This field is required</span>
</div>
<div>
<label for="email">Your Full Email</label>
<input name="email" type="email" id="email" required placeholder="Your Email">
<span id="email_error" class="error_show">This field is required</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<span id="message_error" class="error_show">This field is required</span>
</div>
<div id="contact_submit">
<input type="submit" id="submit_button" value="Submit">
</div>
</form>
</section>
</body>
</html>
var element = $("#contact_submit" + form_data[input]['name'], ['email'], ['message']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
I think these lines don't select the right span.
I got to it on logging the error_element:
console.log(error_element);
Here is a JSFIDDLE with a "working" selector.
var error_element=$("#contact div span");
Now you can change the selector that it fits your needs!