onClick firing multiple times JS - javascript

I've created an HTML form with JS validation. I've called the function through a button via onclick but it is firing multiple times resulting in unnecessary blank form data. Here's the code.
I'm pushing the data to firebase realtime db.
I'm new to JS, any help would be appreciated.
HTML
<form class="subscribe-form" id="subscribe-form">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<input class="email-input" name="email" id="email" type="text" placeholder="Email">
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<button onclick="updateSubscribeEmail();" class="sitebtn btn-submit"
type="submit">Subscribe</button></div>
</form>
JS
function updateSubscribeEmail() {
// Reference messages collection
var messagesRef = firebase.database().ref("Subscription Emails");
var resetForm = document.getElementById("subscribe-form");
// Listen for form submit
document.getElementById("subscribe-form").addEventListener("submit", submitSubscribeForm);
// Submit form
function submitSubscribeForm(e) {
// To avoid entire page getting refreshed
e.preventDefault();
var email = getInputVal("email");
// Get values
var text;
console.log("Before Validation");
if (email.indexOf("#") === -1 || email.length < 6) {
console.log("After Validation");
text = "Please enter a valid email address!";
red_inner_html.innerHTML = text;
red_div.style.display = "block";
setTimeout(function () {
red_div.style.display = "none";
}, 5000);
} else {
saveMessage(email);
console.log("Before reset");
resetForm.reset();
console.log("after reset");
text = "You have successfully subscribed!";
green_inner_html.innerHTML = text;
green_div.style.display = "block";
setTimeout(function () {
green_div.style.display = "none";
}, 5000);
}
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(email) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
Email: email
});
}
}

Related

Problems with form controls in Javascript

I'm working on a project and I am trying to add checks for the inputs on the form. I want it to only submit and move to the URL if the requirements are met. I'm using Javascript to check this. Currently, my code doesn't return any errors in the console but when I press submit even with blank inputs it submits and moves to the next page.
// Form Controls
const form = document.getElementById('form');
const username = document.getElementById('username');
const room = document.getElementById('room');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show Success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldName
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event Listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([username]);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../static/style.css" rel="stylesheet">
<title>ChatR</title>
<script src="{{ url_for('static', filename='scripts.js') }}"></script>
</head>
<body>
<div class="container-head">
<div class="header">
<h1>MyApp</h1>
</div>
</div>
<div class="container">
<form action="{{url_for('chat') }}" class="form" id="form" method="POST">
<div class="form-control">
<input type="username" id="username" name="username" placeholder="Enter username">
<small>Error Message</small>
</div>
<div class="form-control">
<input type="room" id="room" name="room" placeholder="Enter room">
<small>Error Message</small>
</div>
<button type="submit" class="btn btn-big">Start Chat</button>
</form>
</div>
</body>
</html>
New Code that works:
// Check required fields
function checkRequired(inputArr) {
var success = true;
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
success = false;
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
return success;
}
// Check input length
function checkLength(input, min, max) {
var success = true;
if(input.value.length < min) {
showError(input, `${getFieldName(input)} must be at least ${min} characters`);
console.log(input);
success = false;
} else if(input.value.length > max) {
showError(input, `${getFieldName(input)} must be less than ${max} characters`);
success = false;
} else {
showSuccess(input);
}
return success;
}
// Get fieldName
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event Listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
if(checkRequired([username, room]) && checkLength(username, 3, 15)){
form.submit();
}
});
I made some changes to the code so it submits when it is successful.
The first thing is to have checkRequired return true or false indicating if the validation was successful or not.
Second, check that value in the submit event listener and submit the form if it is valid.
// Check required fields, returning true/false if valid.
function checkRequired(inputArr) {
var success = true; // <= assume success
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
success = false; // <= if anything fails, the not successful
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
return success; // return value indicating success
}
// Event Listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
// submit only if validation is successful
if(checkRequired([username, room])){
form.submit();
}
});
By the way, you might want to add room to the array of inputs being validated.
The problem here is Because the element is not found in the DOM while the script is running with this it will run after dom gets loaded.
So solution for this is to add a this line on top of scripts.js
document.addEventListener("DOMContentLoaded", () => {
//whole scripts.js in this section
//ends with this
})
with this it will loads and check if DOM is loaded or not and after that your script will work

Custom event logging multiples

I wrote a custom Javascript event to handle if username exists among the list of users. when there is no user match, it logs fine that there is no user with that name. but the problem is when there is a user match, both if and else runs simultaneously. the code works like this: user types his username, and as soon as the password field is clicked, an event is fired to check if username exists or not. I am new to Javascript am just trying to figure out custom event thanks.
Below is my code:
var user_list = [
{
username:"john",
name:"john.doe",
last_seen:"2mins ago"
},
{
username:"mary",
name:"Mary marta",
last_seen:"2hrs ago"
},
{
username:"susan",
name:"susy457",
last_seen:"45mins ago"
},
{
username:"moses",
name:"moe23",
last_seen:"45mins ago"
},
];
var password = document.getElementById("passwordtext");
password.addEventListener('click', checkPassword);
//Custom event to grab username field when the user is about to type the password
var users = document.getElementById('usertext');
users.addEventListener('trigger', function(e){
var display = e.target.value;//e.target.value
if(display === ""){
//console.log('empty string..');
}else{
for(var i = 0; i < user_list.length; i++){
if(user_list[i].username === display){
console.log('user found..')
}
else{
console.log('user not found!');
}
};
};
event.preventDefault();
});
function checkUser(){
var event = new CustomEvent('trigger');
users.dispatchEvent(event);
};
function checkPassword(e){
checkUser()
passcode = e.target.value;
//console.log(e.target.value);
event.preventDefault();
};
edit: here is my html form code
<form>
<div class="form-row">
<div class="col">
<input type="text" name="usertext" id ="usertext" class="form-control"placeholder="Email or username"/>
</div>
<div class="col">
<input type="password" id ="passwordtext" class="form-control" placeholder="password"/>
</div>
<div class="col-auto">
<a class="btn btn-primary" id="id-login" href="#" role="button">login</a>
</div>
</div>
</form>
Get your check outside of the for loop. See this example.
However there are even easier ways to do it when you just search your Javascript object for the existence of a user instead of looping the object.
var user_list = [{
username: "john",
name: "john.doe",
last_seen: "2mins ago"
},
{
username: "mary",
name: "Mary marta",
last_seen: "2hrs ago"
},
{
username: "susan",
name: "susy457",
last_seen: "45mins ago"
},
{
username: "moses",
name: "moe23",
last_seen: "45mins ago"
},
];
var password = document.getElementById("passwordtext");
password.addEventListener('click', checkPassword);
//Custom event to grab username field when the user is about to type the password
var users = document.getElementById('usertext');
users.addEventListener('trigger', function(e) {
var display = e.target.value; //e.target.value
if (display === "") {
//console.log('empty string..');
} else {
var userFound = false;
for (var i = 0; i < user_list.length; i++) {
if (user_list[i].username === display) {
userFound = true;
break;
}
};
if (userFound) {
console.log('user found!');
} else {
console.log('user not found!');
}
};
event.preventDefault();
});
function checkUser() {
var event = new CustomEvent('trigger');
users.dispatchEvent(event);
};
function checkPassword(e) {
checkUser()
passcode = e.target.value;
//console.log(e.target.value);
event.preventDefault();
};
<form>
<div class="form-row">
<div class="col">
<input type="text" name="usertext" id="usertext" class="form-control" placeholder="Email or username" />
</div>
<div class="col">
<input type="password" id="passwordtext" class="form-control" placeholder="password" />
</div>
<div class="col-auto">
<a class="btn btn-primary" id="id-login" href="#" role="button">login</a>
</div>
</div>
</form>

items won't delete from localStorage with ES6

I've been trying for hours to successfully remove items from a list through the localStorage API. I have no problem with inserting the items into the list and view them as they're being pushed into the view. How can I delete items from an array using localStorage? The code that I wrote is below. One other small issue, the form validation is not kicking in, I can't seem to spot the bug that's allowing null inputs.
index.html
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="shoutout-box-pos">
<div class="shoutout-box">
<div class="shoutout-box-header">
<div class="text-center">
<div class="shoutout-header-text">
<h4>Post a shoutout</h4>
</div>
<div class="shoutout-form-container">
<form id='shoutout-form'>
<div class="form-group">
<label>Name</label>
<input class="form-control" type="text" placeholder="Customer Name" id="name" />
</div>
<div class="form-group">
<label>Tell us about your stay!</label>
<input class="form-control" type="text" placeholder="What would you like to say?" id="message" />
</div>
<div class="form-group">
<label>Which session did you take part in?</label>
<input class="form-control" type="text" id="tour_session" placeholder="Give us the date or session title" />
</div>
<div class="form-group">
<button class="bttn-bordered bttn-md bttn-primary" type="submit" value="Submit">Post Message</button>
</div>
</form>
</div>
<div class="shoutout-messages">
<ul class="messageListContainer" id="messageList">
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
app.js
// ES6 Shoutout Messages
class Shoutout {
constructor(name, message, tour_session) {
this.name = name;
this.message = message;
this.tour_session = tour_session;
}
}
class UI {
addMessageToList(Shoutmessage) {
const list = document.getElementById('messageList');
// create li element
const li = document.createElement('li');
//Insert li into ul
li.innerHTML = `
<li><strong>Customer Name: </strong> <p class='lead'>${Shoutmessage.name}</p></li>
<li><strong>Message: </strong> <p class='lead'> ${Shoutmessage.message}</p></li>
<li><strong>Tour Session: </strong> <p class='lead'> ${Shoutmessage.tour_session} </p></li>
<li><a href="#" class="delete bttn-minimal bttn-sm">Remove Shoutout<a></li>
`;
list.appendChild(li);
}
showAlert(message, className) {
// create div
const div = document.createElement('div');
// Add classes
div.className = `alert ${className}`;
// Add text
div.appendChild(document.createTextNode(message));
// Get Parent Class
const container = document.querySelector('.shoutout-form-container');
// Get form Id
const form = document.querySelector('#shoutout-form');
// Insert alert
container.insertBefore(div, form);
// Timeout after 3 seconds
setTimeout(function () {
document.querySelector('.alert').remove();
}, 3000);
}
deleteShout(target) {
if (target.className === 'delete') {
target.parentElement.parentElement.remove();
}
}
clearFields() {
document.getElementById('name').value = '';
document.getElementById('message').value = '';
document.getElementById('tour_session').value = '';
}
}
// Local Storage Class Object
class Store {
static getShoutouts() {
let messages;
if (localStorage.getItem('messages') === null) {
messages = [];
} else {
messages = JSON.parse(localStorage.getItem('messages'));
}
return messages;
}
static displayShoutouts() {
const messages = Store.getShoutouts();
messages.reverse().forEach(function (message) {
const ui = new UI;
ui.addMessageToList(message);
});
}
static addMessage(message) {
const messages = Store.getShoutouts();
messages.push(message);
localStorage.setItem('messages', JSON.stringify(messages));
}
static removeMessage(tour_session) {
const messages = Store.getShoutouts();
messages.forEach(function (message, index) {
if (message.tour_session === tour_session) {
messages.splice(index, 1);
}
});
localStorage.setItem('messages', JSON.stringify(messages));
}
}
// DOM Load Event
document.addEventListener('DOMContentLoaded', Store.displayShoutouts);
// Event Listener for add message
document.getElementById('shoutout-form').addEventListener('submit', function (e) {
//Grab form values
const name = document.getElementById('name').value,
message = document.getElementById('message').value,
tour_session = document.getElementById('tour_session').value
// Instantiate message
const msg = new Shoutout(name, message, tour_session);
// Instantiate UI
const ui = new UI();
console.log(ui);
// Validate
if (name === '' || message === '' || tour_session === '') {
//Error alert
ui.showAlert('Please fil in all fields', 'error');
} else {
// Add message to list
ui.addMessageToList(msg);
// Add to Local Storage
Store.addMessage(msg);
// Show success
ui.showAlert('Shoutout Message Added!', 'success');
// Clear fields
ui.clearFields();
}
e.preventDefault();
});
// Event Listener for delete
document.getElementById('messageList').addEventListener('click', function (e) {
// Instantiate UI
const ui = new UI();
// Delete message
ui.deleteShout(e.target);
// Remove from Local Storage
Store.removeMessage(e.target.parentElement.previousElementSibling.textContent);
// Show message
ui.showAlert('Message Removed!', 'success');
e.preventDefault();
});
The problem here in your code is that
e.target.parentElement.previousElementSibling.textContent probably returns string like
"Tour Session: ${tour_session}"
while exact tour session, which you need, is inside the element in p.lead
so try to change your tour_session selector to
...
// Remove from Local Storage
Store.removeMessage(e.target.parentElement.previousElementSibling.querySelector(".lead").textContent);
...
UPD
Take a look at this CodePen.
DEMO: https://codepen.io/anon/pen/ajpwYR?editors=0011
In your addMessageToList() method I've added an attribute tour_session to the Remove Shoutout link.
addMessageToList(Shoutmessage) {
const list = document.getElementById('messageList');
// create li element
const li = document.createElement('li');
//Insert li into ul
li.innerHTML = `
<li><strong>Customer Name: </strong> <p class='lead'>${Shoutmessage.name}</p></li>
<li><strong>Message: </strong> <p class='lead'> ${Shoutmessage.message}</p></li>
<li><strong>Tour Session: </strong> <p class='lead'> ${Shoutmessage.tour_session} </p></li>
<li><a href="#" class="delete bttn-minimal bttn-sm" tour_session=${Shoutmessage.tour_session}>Remove Shoutout<a></li>
`;
list.appendChild(li);
}
In the event listener, pass the value of the tour_session attribute to the removeMessage method.
document.getElementById('messageList').addEventListener('click', function(e) {
// Instantiate UI
const ui = new UI();
// Delete message
ui.deleteShout(e.target);
// Remove from Local Storage
// console.log(e.target.getAttribute('tour_session'));
Store.removeMessage(e.target.getAttribute('tour_session'));
// Show message
ui.showAlert('Message Removed!', 'success');
e.preventDefault();
});
In the deleteShout method, the className would return the names of all the classes you've specified. So, your check fails everytime and the node is not removed from the DOM.
deleteShout(target) {
if (target.className.split(' ').indexOf('delete') > -1) {
target.parentElement.parentElement.remove();
}
}

stop loading image on form submit if required field

On https://bm-translations.de/#kontakt I've got a form with a submit button, that is replaced with a loading gif, when clicked.
The problem is: if one of the required fields isnt set, the form does not submit but the loading gif appears and doesnt disappear. How to say only appear if all required fields are set?
This is the HTML:
<div id="formsubmitbutton">
<input type="submit" name="submitter" value="Submit Button" onclick="ButtonClicked()">
</div>
<div id="buttonreplacement" style="margin-left:30px; display:none;">
<img src="./bilder/preload.gif" alt="loading...">
</div>
This is the JS:
function ButtonClicked()
{
document.getElementById("formsubmitbutton").style.display = "none"; // to undisplay
document.getElementById("buttonreplacement").style.display = ""; // to display
return true;
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("formsubmitbutton").style.display = ""; // to display
document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
// To disable restoring submit button, disable or delete next line.
document.onfocus = RestoreSubmitButton;
Here you go with a solution https://jsfiddle.net/z7wfj880/2/
ButtonClicked = function(){
var validate = true;
$('input:required').each(function(){
if($(this).val().trim() === ''){
validate = false;
}
});
if(validate) {
document.getElementById("formsubmitbutton").style.display = "none"; // to undisplay
document.getElementById("buttonreplacement").style.display = ""; // to display
return true;
}
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("formsubmitbutton").style.display = ""; // to display
document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
// To disable restoring submit button, disable or delete next line.
document.onfocus = RestoreSubmitButton;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="First Name" required/>
<input type="text" placeholder="Middle Name"/>
<input type="text" placeholder="Last Name" required/>
<div id="formsubmitbutton">
<input type="submit" name="submitter" value="Submit Button" onclick="ButtonClicked()">
</div>
<div id="buttonreplacement" style="margin-left:30px; display:none;">
<img src="./bilder/preload.gif" alt="loading...">
</div>
First of all do a trim of required input field, so that if any user provide spaces it will remove the extra spaces in front & end.
Loop through all the required input & check for empty input.
You can create a modular function to display and hide the loader.
Now when you click the submit button, you can check for your form validation and toggle the loader easily. I have hardcoded the false, but you can check for the appropriate validation.
function displayLoading(form, loader) {
document.getElementById("formsubmitbutton").style.display = form; // to undisplay
document.getElementById("buttonreplacement").style.display = loader; // to display
}
function ButtonClicked()
{
if(false) { // form in valid
displayLoading('none', '');
} else {
displayLoading('', 'none');
}
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("formsubmitbutton").style.display = ""; // to display
document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
// To disable restoring submit button, disable or delete next line.
document.onfocus = RestoreSubmitButton;
<div id="formsubmitbutton">
<input type="submit" name="submitter" value="Submit Button" onclick="ButtonClicked()">
</div>
<div id="buttonreplacement" style="margin-left:30px; display:none;">
<img src="http://gph.is/1cYmtb9" alt="loading...">
</div>
Check for validation of required fields.
If all fields are set then only call buttonreplacement.
For Eg: If you have fields field1 and field2.
f1 = document.getElementById("id_field1").value;
f2 = document.getElementById("id_field2").value;
if (f1!=null || f1!=undefined || f1!="" || f2!=null || f2!=undefined || f2!=""){
document.getElementById("buttonreplacement").style.display = "none";
}
else{
document.getElementById("buttonreplacement").style.display = "block";
}
You can always improve your code using Jquery.

Javascript/jQuery form validation

I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out a way to make the error text disappear with the way that I am doing this. Also I know I have the option of PHP validation but there is a few reasons why I want to use this front end validation. Here is the whole validation script for the form. The submit portion is at the bottom:
JavaScript/jQuery
var valid = 0;
function checkName(elem) {
//gather the calling elements value
var val = document.getElementById(elem.id).value;
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span>Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
valid++;
}
}
function checkEmail(elem) {
var val = document.getElementById(elem.id).value;
//Check email format validity
var 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,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
valid++;
}
}
function checkMessage(elem) {
var val = document.getElementById(elem.id).value;
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
valid++;
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
function checkSubmit() {
if (valid == 3) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
//If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if (valid < 3) {
document.getElementById("errorSubmit").innerHTML = "<span>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
HTML Form
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="cform" id="contact-form">
<form id="form13" name="form13" role="form" class="contactForm" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate
action="https://Some3rdPartyPOSTService">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" name="Field1" class="form-control" id="name" placeholder="Tony Stark" onblur="checkName(this)"/>
<span id="errorName" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="Field4" id="email" placeholder="" data-rule="email" data-msg="Please enter a valid email" onblur="checkEmail(this)"/>
<span id="errorEmail" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="Field3" id="message" rows="5" data-rule="required" data-msg="Please write something here" onblur="checkMessage(this)"></textarea>
<span id="errorMessage" style="margin-left:10px;"></span>
</div>
<span id="errorSubmit" style="margin-left:10px;"></span>
<button type="submit" class="btn btn-theme pull-left">SEND MESSAGE</button>
</form>
</div>
</div>
<!-- ./span12 -->
</div>
</div>
</section>
Simply put your check on onChange event callback, if:
var x = getElementById("formid"); // then add a listener
x.addEventListener('change', function () {
callback with your code that examines the form
});
Or listen for a specific text box change event, that would be the simplest way, and look for a way to disable submit if the conditions aren't met.
Add an onchange event to your text inputs that will remove the error message.
Rather than making a count of valid fields, I would also check for the existence of error messages. This will make it easier to add more fields to your form.
function checkName(e) {
//gather the calling elements value
var val = $(e.target).val();
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span class="errmsg">Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span class='errmsg'>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
}
}
function checkEmail(e) {
var val = $(e.target).val();
//Check email format validity
var 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,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span class='errmsg'>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
}
}
function checkMessage(e) {
var val = $(e.target).val();
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
$('#name').change(checkName);
$('#email').change(checkEmail);
$('#message').change(checkMessage);
function checkSubmit() {
if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
}
/If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
Since you were already using jQuery, I modified the code to use more of the jQuery functionality to make things easier. Now when a form field is modified and the element loses focus, the validation will occur immediately. We also no longer need to know how many error messages could potentially appear (though you never had a decrement operation for corrected values so the valid could become greater than 3). Instead we just make sure that there isn't more than 0 of them.
I've removed your onblur html attributes and replaced them by JavaScript keyup events. This will allow your script to check everything as soon as the user type something :
document.getElementById("message").addEventListener('keyup', function () {
checkMessage(this);
});
document.getElementById("email").addEventListener('keyup', function () {
checkEmail(this);
});
document.getElementById("name").addEventListener('keyup', function () {
checkName(this);
});
JSFIDDLE

Categories

Resources