I am quite new to javascript and am trying to make a validation form that validates once you click out of the input field. I have been trying out many different ways to add on blur to a current validating form which I have created.
How could I add on blur to my validation form? Thanks :)
function addFormValidation(theForm) {
if (theForm === null || theForm.tagName.toUpperCase() !== 'FORM') {
throw new Error("expected first parameter to addFormValidation to be a FORM.");
}
theForm.noValidate = true;
theForm.addEventListener('submit', function(evt) {
var isError = false;
var elements = this.elements;
for (var i = 0; i < elements.length; i += 1) {
if (! isFieldValid(elements[i])) {
isError = true;
}
}
if (isError) {
evt.preventDefault();
}
});
function isFieldValid(field) {
var errorMessage = "";
if (! needsToBeValidated(field)) {
return true;
}
if (field.id.length === 0 || field.name.length === 0) {
console.error("error: ", field);
throw new Error("found a field that is missing an id and/or name attribute. name should be there. id is required for determining the field's error message element.");
}
field.classList.remove('invalid');
var errorSpan = document.querySelector('#' + field.id + '-error');
if (errorSpan === null) {
console.error("error: ", field);
throw new Error("could not find the '#" + field.id + "-error' element. It's needed for error messages if #" + field.id + " is ever invalid.");
}
errorSpan.classList.remove('danger');
errorSpan.innerHTML = "";
if (field.minLength > 0 && field.value.length < field.minLength) {
errorMessage = "Must be " + field.minLength + " or more characters long.";
}
if (field.type === "email" && !isEmail(field.value)) {
errorMessage = "This should be a valid email address.";
}
if (field.required && field.value.trim() === "") {
errorMessage = "This field is required.";
}
if (errorMessage !== "") {
field.classList.add('invalid');
errorSpan.classList.add('danger');
errorSpan.innerHTML = errorMessage;
return false;
}
return true;
}
function needsToBeValidated(field) {
return ['submit', 'reset', 'button', 'hidden', 'fieldset'].indexOf(field.type) === -1;
}
function isEmail(input) {
return input.match(/^([a-z0-9_.\-+]+)#([\da-z.\-]+)\.([a-z\.]{2,})$/);
}
}
HTML
<div class="content">
<form id="contact-form" method="POST" action="success.html">
<div class="form-group">
<label for="firstname">First Name</label>
<input id="firstname" type="text" name="firstname" value="" onblur="addFormValidation('firstname');"/>
<span id="firstname-error"></span>
</div>
<div class="form-group">
<label for="lastname">Last Name</label>
<input id="lastname" type="text" name="lastname" onblur="addFormValidation('lastname');">
<span id= "lastname-error" ></span>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input id="email" type="email" name="email" required>
<span id="email-error"></span>
</div>
<div class="form-group">
<label for="flight">Flight</label>
<select name="flight" id="flight" required>
<option value="">Please select a flight</option>
<option value="1">Fixed Wing</option>
<option value="2">Helicopter</option>
<option value="3">Glider</option>
</select>
<span id="flight-error"></span>
</div>
<div class="form-group">
<label for="date">Date</label>
<input id="date" type="date" name="date" required>
<span id="date-error"></span>
</div>
<div class="form-group">
<label for="time">Time</label>
<input id="time" type="time" name="time" required>
<span id="time-error"></span>
</div>
<div class="form-group">
<label for="duration">Duration</label>
<select name="duration" id="duration" required>
<option value="">Please select your desired duration</option>
<option value="1">1 Hour</option>
<option value="2">2 Hours</option>
<option value="3">3 Hours</option>
<option value="4">4 Hours</option>
<option value="5">5 Hours</option>
</select>
<span id="duration-error"></span>
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
addFormValidation(document.querySelector('#contact-form'));
});
</script>
http://jsfiddle.net/dLz5w2tz/
I always recommend not using element attributes (onblur) for javascript event execution; instead you can add the listener to your javascript code.
I've done the following to your code:
Remove "onblur" attributes
Add code in your JS to listen to blur events on the entire form (all elements).
JS snipped
theForm.addEventListener('blur', function(evt) {
console.log(evt);
}, true);
Updated JS Fiddle: http://jsfiddle.net/dLz5w2tz/1/
Note:
addEventListner takes 3 parameters -
1. "event"
2. function to execute
3. boolean - should it bubble/propagate the event upwards.
So basically, in this code, the event takes place on the form element (input) and bubbles up to the form itself. You can verify this by looking at the event variable (evt).
Related
`I've created a form that allows a user to enter their details and have their first and last names displayed along with a numerical ID. There is a 'Delete' button allowing the user to remove whatever name they select.
by default, the 'Delete' button should be disabled until the <select> list is populated. If all names are deleted from the list - the 'Delete' button should disable again.
That's where im struggling. I cant get the 'Delete' button to enable when a name is added to the list.
Below is my HTML and JavaScript:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.value === 1;
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
console.log("is remove being triggered??")
}
if (Member.options.length == ""){
Delete.disabled = true
}
else {
Delete.disabled = false
}
</script>
</body>
`
The reason why the Delete button is not enabling is because the code that is supposed to enable the Delete button is only run once, when the page loads.
Assuming that this is the code that is supposed to enable the button:
if (Member.options.length == 0){ // changed from Member.options.length == ""
Delete.disabled = true
} else {
Delete.disabled = false
}
This code is only run once, when the page loads and the JavaScript code is run. In order to enable the button properly, we need to run this code every time that Member.options.length changes. One way you can do this is place the code snippet above for disabling/enabling the Delete button inside the onclick listener for the save button and to re-check every time a new user is saved. You would have to add this snippet into every place in your code where Member.options.length could change (inside the listener for the delete button as well).
Full updated code:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.options.length == 0
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
if (Member.options.length == 0){
Delete.disabled = true
}
else {
Delete.disabled = false
}
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
if (Member.options.length == 0) {
Delete.disabled = true
}
else {
Delete.disabled = false
}
console.log("is remove being triggered??")
}
</script>
</body>
so if i understood correctly you want to toggle a button if a is populated
In that case you want to keep track of the options
You can use
document.querySelectoAll('options')
and store it in a variable
then write a function that check if there's a value in that variable and disable or enable the button based on that.
Here's a fiddle:
https://jsfiddle.net/skm7bcr6/15/
I'm trying to input something into a text field based on an option selected from a dropdown, using .val(), but it is not working.
$('#addressee_type').on('change', function() {
var type = $("select#addressee_type option:selected").attr('value');
// alert(type);
if (type == 'I') {
$('#name').attr('required', true).val('insured')
} else if (type == 'A') {
$('#name').attr('required', true).val('third party adv')
} else if (type == 'C') {
$('#name').attr('required', true).val('third party')
} else {
$('#name').attr('required', true).val('')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4">
<label class="required">Addressee type</label>
<select class="form-control chosen" id="addressee_type" name="addressee_type" required>
<option value="" selected>Please select Addressee type</option>
<option value="I">Insured</option>
<option value="A">Third Party Advocate</option>
<option value="C">Third Party Claimant</option>
</select>
</div>
<div class="col-sm-4">
<label class='required'>Addressee Name</label>
<input class="form-control" readonly="true" id="name" type="text" name="name">
</div>
I added the attr() later on from a solution I found, but it still didn't solve the error.
Does anyone have an idea?
So basically, I'm trying to do client side validation through JavaScript, but the code does not seem to be working. I am not getting any alert box. Below is HTML Form and JavaScript. I have skipped html and Body tags for obvious reasons. Can someone look over and see where am I making a mistake?
HTML form
<div class="container" >
<h1 style="text-align: center;">Online Vaccine Registration Form</h1>
<h1 style="text-align: center;">Developed by yourname</h1>
<form method="post" name="vacform" onsubmit=" return validateForm()">
<table>
<div class="row">
<div class="form-group col-md-6">
<label for="Name">Name : </label>
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
<div class="form-group col-md-6">
<label for="CNIC" >CNIC : </label>
<input type="text" class="form-control" name="CNIC" placeholder="CNIC">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="Mob">Mobile : </label>
<input type="number" class="form-control" name="Mob" placeholder="Mobile">
</div>
<div class="form-group col-md-6">
<label for="Dob" >DoB : </label>
<input type="date" class="form-control" name="DoB">
</div>
</div>
<div class="form-group">
<label for="cen">Nearby centre</label>
<select class="form-control" id="sel1">
<option selected disabled>Select your Nearest Centre</option>
<option>Karachi West</option>
<option>Karachi East</option>
<option>Karachi North</option>
<option>Karachi Central</option>
<option>Malir</option>
</select>
</div>
</table>
<button type="button" class="btn btn-primary">Submit</button>
</form>
</div>
JavaScript
function validateForm()
{
var varname = document.vacform.name.value;
var varcnic = document.vacform.CNIC.value;
var varMob = document.vacform.Mob.value;
var varDoB = new Date(DoB);
var limitdate = new Date('2010-01-01');
var CNlength = 13;
var num = /^[0-9]+$/;
var str = /^[A-Za-z]+$/;
if(document.vacform.name.value!="")
{
if(document.vacform.CNIC.value!="")
{
if(document.vacform.Mob.value!="")
{
if(document.vacform.DoB.value!="")
{
if(varname.match(str))
{
if(varcnic.lenght == CNlength)
{
if(varcnic.match(num))
{
if(varDoB.getYear() < limitdate.getYear())
{
alert("All types of Validations have been done")
return true;
}
else
{
alert("Date should be less than 01-01-2010")
return false;
}
}
else
{
alert("CNIC field should have numbers only")
return false;
}
}
else
{
alert("CNIC lenght should be 13")
return false;
}
}
else
{
alert("Name can only contain letters")
return false;
}
}
else
{
alert("Date of Birth must be entered")
return false;
}
}
else
{
alert("Please Enter your mobile number")
return false;
}
}
else
{
alert("CNIC number Required")
return false;
}
}
else
{
alert("Name field can not be empty")
return false;
}
}
</script>
You call the function from the onsubmit event handler, however you never submit the form so it can't be triggered.
<button type="button" class="btn btn-primary">Submit</button>
This kind of button is for hooking JS into. It isn't a submit button.
Set type="submit" or remove the type attribute entirely (submit is the default).
Also address the errors in your HTML that a validator would highlight.
I have a basic form with some input fields and a dropdown(select field).
Almost all fields have a form of validation. When a field has an error, an error message with the CSS class 'errorText' is displayed next to the field.
By default, my submit button is 'disabled'. I want to remove the 'disabled' attribute from my submit button once all tags with 'errorText' CSS classes are hidden/removed.
my current script just hides all tags with 'errorText' when an error occurs. how do I stop it from doing that and how can I enable my submit button once all fields have been properly enter/validated? Thanks.
EDIT: SOLVED. CODE UPDATED.
// Field Validations
$('#firstName')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$('label[for="firstName"]').addClass('errorText');
$('#errorFName').show();
} else {
$('label[for="firstName"]').removeClass('errorText');
$('#errorFName').hide();
}
});
$('#lastName')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$('label[for="lastName"]').addClass('errorText');
$('#errorLName').show();
} else {
$('label[for="lastName"]').removeClass('errorText');
$('#errorLName').hide();
}
});
$('#state')
.on('blur', function() {
var $this = $(this);
if ($('#state').val() == "") {
$('label[for="state"]').addClass('errorText');
$('#errorState').show();
} else {
$('label[for="state"]').removeClass('errorText');
$('#errorState').hide();
}
});
// Submit Button validation
$('input, select').on('keyup, blur', function() {
if ($('.errorText:visible').length ||
$('#firstName' || '#lastName' || '#state').val() == '' ) {
$('input[type="submit"]').prop('disabled', true);
} else if ($('#firstName').val() != '' &&
$('#lastName').val() != '' &&
$('#state').val() != '' ) {
$('input[type="submit"]').prop('disabled', false);
}
});
.errorText {
color: #c4161c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div>
<label for="firstName" class="required">First Name</label>
</div>
<div>
<input type="text" name="firstName" id="firstName" />
</div>
<div class="errorText" id="errorFName" style="display:none;">Please enter a First Name</div>
<br />
<div>
<label for="lastName" class="required">Last Name</label>
</div>
<div>
<input type="text" name="lastName" id="lastName" />
</div>
<div class="errorText" id="errorLName" style="display:none;">Please enter a Last Name</div>
<br />
<div>
<label for="state" class="required">State</label>
</div>
<div>
<select name="state" id="state">
<option value="">Select State</option>
<option value="alabama">Alabama</option>
<option value="alaska">Alaska</option>
<option value="arizona">Arizona</option>
<option value="arkansas">Arkansas</option>
<option value="california">California</option>
<option value="etc">etc..</option>
</select>
</div>
<div class="errorText" id="errorState" style="display:none;">Please select a State</div>
<br />
<input type="submit" class="LargeButton" value="Submit Referral" disabled />
If it helps, check this update using data-attribute. We group the label,input,error in a div and handle error message. Also simplified the check valid on input and select element but can be modified.
html
<div>
<label for="firstName" class="required">First Name</label>
<input type="text" name="firstName" id="firstName" />
<span class="errorText" style="display:none;">Please enter a First Name</span>
</div>
<br />
<div>
<label for="lastName" class="required">Last Name</label>
<input type="text" name="lastName" id="lastName" />
<span class="errorText" style="display:none;">Please enter a Last Name</span>
</div>
<br />
<div>
<label for="state" class="required">State</label>
<select name="state" id="state" data-valid="">
<option value="">Select State</option>
<option value="alabama">Alabama</option>
<option value="alaska">Alaska</option>
<option value="arizona">Arizona</option>
<option value="arkansas">Arkansas</option>
<option value="california">California</option>
<option value="etc">etc..</option>
</select>
<span class="errorText" style="display:none;">Please select a State</span>
</div>
<br />
<input type="submit" id="submit" class="LargeButton" value="Submit Referral" disabled />
script
$(function() {
$('input,select')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$this.data("valid", 'false');
//find the immediate span with errorText and show it
$this.next("span.errorText").show();
} else {
$this.data("valid", 'true');
$this.next("span.errorText").hide();
}
checkInputs();
});
});
function checkInputs() {
//find all the input and select items where the data attribute valid is present and make an array
var array = $('input,select').map(function() {
return $(this).data("valid");
}).get();
//if there are not empty or false indicating invalid value set submit property to true
if (array.indexOf("") == -1 && array.indexOf("false") == -1) {
$("#submit").prop("disabled", false);
} else {
$("#submit").prop("disabled", true);
}
}
css
.errorText {
color: #c4161c;
display: block;
}
I am trying to get a form with multiple fields validate when the submit button is pressed.
If a field is invalid then a message appears next to the field. I can get one of the invalid messages to appear but not all of them. The function I am using is below.
function checkForm() {
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("errEmail").style.display="inline";
return false;
}
if(document.getElementById("fname").value==""){
document.getElementById("errfName").style.display="inline";
return false;
}
else {
return true;
}
if(document.getElementById("lname").value==""){
document.getElementById("errlName").style.display="inline";
return false;
}
else {
return true;
}
}
}
html below
<form name ="reg" id="test">
<fieldset id="controls">
<div>
<label for="title">Title: </label>
<select id="titles">
<option value="mr" selected="selected">Title</option>
<option value="mr">Mr.</option>
<option value="mrs">Mrs.</option>
<option value="ms">Ms.</option>
<option value="miss">Miss</option>
</select>
</div>
<div>
<label for="fname">First Name: </label>
<input id="fname" type="text"><span id="errfName" class="error">* Please Enter a First Name</span>
</div>
<div>
<label for="lname">Last Name: </label>
<input id="lname" type="text"><span id="errlName" class="error">* Please Enter a Last Name</span>
</div>
<div>
<label for="email">Email: </label>
<input id="email" type="text" size="40"><span id="errEmail" class="error">* Please enter a valid email</span>
</div>
<div>
<input type="submit" value="submit">
</div>
</fieldset>
</form>
</body>
</html>
try this:
function checkForm() {
var errors = [];
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
errors.push("errEmail");
}
if(document.getElementById("fname").value==""){
errors.push("errfName");
}
if(document.getElementById("lname").value==""){
errors.push("errlName");
}
if(errors.length > 0 ){
for(var i=0;i<errors.length;i++){
document.getElementById(errors[i]).style.display="inline";
}
return false;
}else{
return true
}
}
}