Radio button validation alert not showing - works on everything else - javascript

I'm creating a cfmail form for a nonprofit to allow potential vendors to request a spot at the next fundraiser. All fields are required but the radio buttons are not showing the validation alert if not selected.
EDIT:
I need the user to check either Yes or No when asked "Will vendor be selling at the event?" If the user checks "Yes", we'll display additional fields (State Tax ID and a textarea asking for more details on their product) that will be REQUIRED. If the user selects "NO" the TaxID and Details will NOT be required but we will be eventually be adding questions as to if they're a 501c3 or not.
I'm javascript illiterate so I had someone else write the JS but she had to move on to other obligations before getting the radio buttons working and I need this working before she'll have time to get back to it. Any help would be greatly appreciated.
Here's the Code:
// phone number
function phoneFormat(input) { //returns (###) ###-####
input = input.replace(/\D/g, '');
var size = input.length;
if (size > 0) {
input = "(" + input
}
if (size > 3) {
input = input.slice(0, 4) + ") " + input.slice(4, 11)
}
if (size > 6) {
input = input.slice(0, 9) + "-" + input.slice(9)
}
return input;
}
$(document).ready(function() {
$("#submitall").click(function() {
if (oked) {
$('#submitall').prop('disabled', true);
$("#submitall").html("Sending...");
$("#submitall").submit();
}
});
$('#salesyes').click(function() {
if ($('#salesyes').is(':checked')) {
$("#statesales").css("display", "block");
$("#StateTaxNumber").prop('required', true);
$("#Details").prop('required', true);
} else {
$("#statesales").css("display", "none");
$("#StateTaxNumber").prop('required', false);
$("#Details").prop('required', false);
}
});
$('#salesno').click(function() {
if ($('#salesno').is(':checked')) {
$("#statesales").css("display", "none");
$("#StateTaxNumber").prop('required', false);
$("#Details").prop('required', false);
} else {
$("#statesales").css("display", "block");
$("#StateTaxNumber").prop('required', true);
$("#Details").prop('required', true);
}
});
});
function countChecked() {
//$("#validateSend").bind('change', function() {
console.log("validateSend clicked");
var cBox = $("#validateSend");
console.log(cBox);
console.log(cBox.prop('checked'));
if (cBox.prop('checked')) {
$('#submitall').prop('disabled', false);
} else {
$('#submitall').prop('disabled', true);
}
}; //end countchecked
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false || $('input[name="Sales"]:checked').length == 0) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- vendor app -->
<div class="container mt-2">
<div class="row justify-content-center mt-5">
<div class="col-sm-12 col-md-10 Sponsors text-center">
<form class="needs-validation" action="/Vendors/index.cfm" id="Vendors" method="post" novalidate>
<input type="hidden" name="Vendors_submit" value="yes">
<!-- company name -->
<div class="form-group row">
<label for="Company" class="form-label text-right">Business/Organization:<sup class="text-danger">*</sup></label>
<input id="Company" name="Company" placeholder="Business/Organization Name" type="text" class="form-control" style="text-transform: capitalize;" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter the name of the company or individual interested in the Vendor spot.
</div>
</div>
<!-- phone -->
<div class="form-group row">
<label for="Phone" class="form-label text-right">Phone:<sup class="text-danger">*</sup></label>
<input id="phone" name="phone" type="tel" placeholder="(555) 555-5555" class="form-control input-md" onInput="this.value = phoneFormat(this.value)" />
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter your phone number.
</div>
</div>
<!-- is vendor selling? -->
<div class="form-group row mt-5">
<div class="col-12 text-center">
<strong>Will vendor be selling at the event?<sup class="text-danger">*</sup></strong>
</div>
</div>
<div class="form-group row">
<div class="col-12 text-center my-auto">
<input class="align-left" type="radio" name="Sales" id="salesyes" value="Yes" required> Yes
<input class="align-left ml-5" type="radio" name="Sales" id="salesno" value="No"> No
</div>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-center">
Please select Yes or No.
</div>
</div>
<!-- State Sales Tax certificate -->
<div id="statesales" style="display:none">
<div class="form-group row">
<div class="col-12 text-left font-italic text-danger mb-4">
Some notice stuff here.
</div>
</div>
<div class="form-group row">
<label for="StateTaxNumber" class="form-label text-left">State Sales Tax Number:<sup class="text-danger">*</sup></label>
<input id="StateTaxNumber" name="StateTaxNumber" placeholder="State Sales Tax Number if applicable" type="text" class="form-control">
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter State sales tax number.
</div>
</div>
<!-- details -->
<div class="form-group row">
<label for="Details" class="form-label">Please describe product or service for sale:<sup class="text-danger">*</sup></label>
<textarea id="Details" name="Details" cols="40" rows="5" class="form-control"></textarea>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter your details.
</div>
</div>
</div>
<!--./end display-none -->
<!-- agree to regulations / restrictions -->
<div class="form-group row justify-content-center">
<div class="col-10 text-center my-auto text-danger">
<input type="checkbox" name="validateSend" id="validateSend" value="1" onclick="countChecked();" /><sup class="text-danger">*</sup>
<i>I have read and understand all the Park's rules and regulations as well as the Requirements and Restrictions listed above.<sup class="text-danger">*</sup>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter your details.
</div>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<button name="submitall" id="submitall" type="submit" class="btn btn-lg btn-danger mt-4 ml-2 text-center" disabled="disabled">Send Request</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>

Related

Validate form with bootstrap (novalidate)

I have a problem validating a form with bootstrap novalidate.
Some form fields include the "required" tag and others do not.
To verify, I submit the form with no data and the 'was-validated' class makes all the fields validated, the ones with the "required" tag are marked in red and the others in green.
The idea is to specify which fields to validate instead of the entire form.
Could you help me please?
Form
<form id="Data" method="POST" class="needs-validation mt-0" novalidate>
<div class="row mb-1">
<div class="col-lg-12 ">
<div class="form-group">
<label class="d-block font-weight-semibold">Name: <span class="text-danger">*</span></label>
<input type="text" id="name" name="Name" class="form-control" autocomplete="off" required>
</div>
</div> <!-- / col -->
</div> <!-- / row-->
<div class="row mb-1">
<div class="col-lg-12 ">
<div class="form-group">
<label class="d-block font-weight-semibold">Lastname: <span class="text-danger">*</span></label>
<input type="text" id="lastname" name="lastname" class="form-control" autocomplete="off" required>
</div>
</div> <!-- / col -->
</div> <!-- / row-->
<div class="row mb-1">
<div class="col-lg-12 ">
<div class="form-group">
<label class="d-block font-weight-semibold">Street: <span class="text-danger">*</span></label>
<input type="number" id="Street" name="Street" class="form-control">
</div>
</div> <!-- / col -->
</div> <!-- / row-->
</form>
JS
<script type="text/javascript">
$('#Data').on('submit', function(e){
e.preventDefault();
var form = document.getElementById('Data');
if (!form.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
else {
$.ajax({
//url: "",
type: $('#Data').attr('method'),
data: $('#Data').serialize(),
//dataType: 'json',
beforeSend: function(){ },
success:function(response) {
if (response.success == true) {
}
else {
}
}
})
}
$('#Data').addClass('was-validated');
});
</script>
Call checkValidity() for each field that need checking, not the complete form:
var formFlag = true;
var nameField = document.getElementById("name");
if (!nameField.checkValidity()) {
nameField.classList.add("is-invalid");
formFlag = false;
}
var lastnameField = document.getElementById("lastname");
if (!lastnameField.checkValidity()) {
lastnameField.classList.add("is-invalid");
formFlag = false;
}
if (!formFlag) {
e.preventDefault();
e.stopPropagation();
return;
} else {

show/hide dynamic error messages and prevent default

I've got a simple form to validate and I can't use jQuery validate().
I've made two error messages - one for a checkbox group and one for an email confirmation mismatch.
Here is the form
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>testForm</title>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div class="container main">
<div class="row">
<div class="col-sm-8 col-sm-offset-2 logo">
<p class="text-center">Use this form to request more information.</p>
<div class="well">
<form name="enrol" id="enrol" xmp-register class="form-horizontal">
<div class="form-group" id="checkboxGroup">
<div class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8">
<div class="checkbox">
<label>
<input type="checkbox" id="flexi" name="checkBoxes"> Yes, email me more information about Scheme 1</label>
</div>
</div>
<div class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8">
<div class="checkbox">
<label>
<input type="checkbox" id="kiwi" name="checkBoxes"> Yes, email me more information about Scheme 2</label>
</div>
</div>
<div class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8">
<div class="checkbox">
<label>
<input type="checkbox" id="protect" checkBoxes="protect"> Yes, email me more information about Scheme 3</label>
</div>
</div>
</div>
<div class="form-group">
<label for="firstName" class="col-md-3 col-lg-4 control-label"> First name </label>
<div class="col-md-8 col-lg-7">
<input type="text" name="firstName" maxlength="42" class="form-control" required>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-md-3 col-lg-4 control-label"> Last name </label>
<div class="col-md-8 col-lg-7">
<input type="text" name="lastName" maxlength="42" class="form-control" required>
</div>
</div>
<div id="emailGroup">
<div class="form-group">
<label for="email" class="col-md-3 col-lg-4 control-label"> Email address </label>
<div class="col-md-8 col-lg-7">
<input type="email" id="email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<label for="confirmEmail" class="col-md-3 col-lg-4 control-label"> Confirm email address </label>
<div class="col-md-8 col-lg-7">
<input type="email" id="confirmEmail" name="confirmEmail" class="form-control" required>
</div>
</div>
</div>
<div class="form-group">
<label for="contact-number" class="col-md-3 col-lg-4 control-label"> Contact number </label>
<div class="col-md-4">
<input type="text" name="contactNumber" class="form-control" pattern="\d+">
</div>
<div class="col-md-4 col-lg-3">
<select name="contactNumberType" class="form-control">
<option value="" disabled="disabled" selected="selected">Type</option>
<option value="mobile">Mobile</option>
<option value="business-hours">Business Hours</option>
<option value="after-hours">After Hours</option>
</select>
</div>
</div>
<div class="form-group">
<label for="memberNumber" class="col-md-3 col-lg-4 control-label" style="padding-top:0px;"> Member number
<br>(if you already have one)</label>
<div class="col-md-8 col-lg-7">
<input type="number" name="memberNumber" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-3 col-md-offset-1">
<input id="submitBtn" name="submitBtn" type="submit" value="Complete" class="form-control btn btn-primary">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!--[if lte IE 7]>
<script src="https://raw.github.com/mattpowell/localstorageshim/master/localstorageshim.min.js" type="text/javascript"></script>
<![endif]-->
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- WM coding -->
<script src="so.js"></script>
</body>
</html>
and here is the JS
$(document).ready(function () {
// set flags to control error messages
var emailError = false;
var selectionError=false;
$("#submitBtn").click({
// validation checks performed on submit:
// 1. check that at least one checkbox is checked
emailError,selectionError // passing parameters to click function
}, function (event) {
var flexibox = document.getElementById("flexi");
var kiwibox = document.getElementById("kiwi");
var protectbox = document.getElementById("protect");
var mainEmail = document.getElementById("email").value;
var confirmEmail = document.getElementById("confirmEmail").value;
var noSelection = checkRequest(); // check if selection made
var emailMismatch = checkEmails(mainEmail, confirmEmail);
console.log(noSelection);
if (noSelection || emailMismatch) { // checks the first element of variable returned
event.preventDefault();
}
function checkRequest() {
if (protectbox.checked == false && (kiwibox.checked == false && flexibox.checked == false)) { //no option selected
if (selectionError === false) { // if no error message showing
$("#checkboxGroup").after( // add error message
'<div id="noSelect" class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8"><p style="color:red;">Please select at least one option.</p></div>'
);
selectionError = true; //update flag to avoid multiple error messages on repeated submit attempts
}
return selectionError; // exit
} else { // something is selected
$("#noSelect").remove(); // remove error message
selectionError=false; //reset flag
return selectionError; //exit
}
}
function checkEmails(mainEmail, confirmEmail) {
if (mainEmail != confirmEmail) { //2. email addresses don't match
if (emailError === false) { // if no error message showing
$("#emailGroup").after( // add error message
'<div id="emailMismatch" class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8"><p style=color:red;">Please ensure the email addresses match.</p></div>'
);
emailError = true; //update flag to avoid multiple error messages on repeated submit attempts
}
return true;
} else if (mainEmail == "" || confirmEmail == "") { // to stop email error message showing when the fields haven't been filled
return emailError;
} else {
return emailError;
}
}
});
});
// force Sarari to honour required attributes
jQuery.getScript('https://cdnjs.cloudflare.com/ajax/libs/webshim/1.15.7/minified/polyfiller.js')     .done(function () {         
webshims.polyfill('forms');          
});
The problem I'm having is that the checkbox group error message hides and shows each time a submit attempt is made - works OK, but the email mismatch error shows once and then can't be removed and the form won't submit, even when an email mismatch has been corrected.
When I inspect the page in Chrome and step through the code, I can see that the two variables for the email check, "mainEmail" and "confirmEmail" do match, but the following statements are skipped as if they do not match.
If anyone could give me some help with this I'd be really grateful. I'm sure that the code is unnecessarily lengthy - I'm pretty much a beginner.
Thanks and regards,
Malcolm
You're not unsetting the error message nor setting emailError to false . Change the else block of checkEmail to
else {
emailError = false;
$("emailMismatch").remove();
return emailError;
}

Form validation with multiple highlighted fields

I have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.

JQuery Bootstrap Modal auto calculate text field not updating

I have a bootstrap html page that contains already 2 auto update text field functions for its needs. Along with that I added another fields in a modal to complete the page and requires another auto calculation to be populated on a certain text field.
Base form for first and 2nd instance of auto update
<form role="form" id="myForm" action="cashier.php?submit=yes" method="post" data-toggle="validator">
<div class="form-group">
<div class="row">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Item</label>
<select onchange="GenPrice(this)" id="items" name="items" class="form-control" required>
<option value="" selected disabled>Select Item</option>
<?php
//some sql function for fetch
echo '<option value="'.$row['sup_eaprice'].'|'.$row['sup_name'].'" required>'.$row['sup_name'].'</option>';
}
}
?>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//FIRST INSTANCE AUTO UPDATING TEXT FIELD
<label for="exampleInputEmail1">Price (ea)</label>
<input type="text" class="form-control" id="eaprice" placeholder="No Item Selected" required disabled>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Quantity</label>
<input type="text" class="form-control calculate" onchange="GenTot(this)" name="quantity" id="quantity" placeholder="How many?" pattern="^[0-9]*[1-9][0-9]*$" maxlength="3" data-minlength="1" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//2ND INSTANCE AUTO UPDATING TEXTFIELD
<label for="exampleInputEmail1">Total</label>
<input type="text" class="form-control" id="ztotal" name="ztotal" readonly>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group" align="right">
<button id="submit" type="submit" class="btn btn-primary" name="addcart">Add Cart</button>
</div>
</div>
</form>
Modal window 3rd instance
<!--create confirmation modal window-->
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<b>Final Check</b>
</div>
<div class="modal-body">
<div class="row">
<form role="form" id="purchformx" action="cashier.php?submit=yes" method="post" data-toggle="validator">
<!-- hidden for purpose of change auto calc -->
<input type="hidden" name="thetotal" class="calchange" id="thetotal" value="<?php echo $overall; ?>">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Received</label>
<input type="text" class="form-control calchange" name="received" id="received" placeholder="How much given?" pattern="^[0-9]*[1-9][0-9]*$" maxlength="4" data-minlength="1" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//3RD INSTANCE AUTO UPDATE NOT WORKING
<label for="exampleInputEmail1">Change</label>
<input type="text" class="form-control" id="thechange" name="thechange" readonly>
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
Submit
</div>
</div>
</div>
</div>
<!--end modal-->
JQUERIES
For first instance (working)
<script type="text/javascript">
function GenPrice(data) {
var xprice = data.value;
var zprice = xprice.split("|");
document.getElementById ("eaprice").value = zprice[0];
document.myForm.eaprice.value = zprice[0];
}
</script>
For second instance (working) based from Calculate total value inline form
<script type="text/javascript">
/* total value calculator */
$(document).ready(function () {
//Calculate both inputs value on the fly
$('.calculate').keyup(function () {
var Tot = parseFloat($('#eaprice').val()) * parseInt($('#quantity').val());
if(isNaN(Tot)) Tot = "";
$('#ztotal').val(Tot);
});
//Clear both inputs first time when user focus on each inputs and clear value 00
$('.calculate').focus(function (event) {
$(this).val("").unbind(event);
});
});
</script>
For third instance (not working) based from auto calculate total value
<script type="text/javascript">
$(document).ready(function(){
$('.calchange').change(function(){
var total = 0;
$('.calchange').each(function(){
if($(this).val() != '')
{
total = parseFloat($(this).val()) - parseFloat($('#thetotal').val());
}
});
$('#thechange').html(total);
});
})(jQuery);
</script>
I'm not sure why the 3rd instance which is inside a modal window doesn't auto update at all given ive just made a separate jquery class for it. Thanks in advance for further suggestions.
$('.calchange').change(function(){
var total = 0;
$('.calchange').each(function(){
if($(this).val() != '') {
total += parseFloat($(this).val());
}
});
var totalFinal = total - parseFloat($('#thetotal').val());
$('#thechange').val(totalFinal);
});

Validation of code

I have developed some code in bootstrap and I am getting an error while I was validating the fields (name, email). Please help me out.
This is the code for the form:
<div class="container">
<h3 class="text-center">CONTACT</h3>
<p class="text-center"><em>I love my Fans!</em></p>
<div class="row test">
<div class="col-md-4">
<p><span class="glyphicon glyphicon-map-marker"></span>4429, Rainier Street, Irving, Texas ,United States</p>
<p><span class="glyphicon glyphicon-phone"></span>Phone:Phone</p>
<p><span class="glyphicon glyphicon-envelope"></span>Email: Email</p>
</div>
<div class="col-md-8">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form control" id="name" placeholder="Name" type="text" onBlur="txt_Blur(this,'errorName')" />
<span id="errorName" style="display:none;">Please enter a valid name!</span>
</div>
<div class="col-sm-6 form-group">
<input class="form control" id="email" name="email" placeholder="Email" type="email" required>
<span id="errorName" style="display:none;">Please enter a valid email!</span>
</div>
</div>
<div class="textarea">
<textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea>
<span id="errorName" style="display:none">Please enter your comments!</span>
</div>
<br>
<div class="row">
<div class="col-md-12 form-group">
<button class="btn pull-right" type="submit" onclick="button_Click()">Send</button>
</div>
</div>
</div>
</div>
</div>
The JavaScript for validation below:
function txt_Blur(ref, errorId) {
if (ref.value == "") {
document.getElementById(errorId).style = "color:red;";
} else {
document.getElementById(errorId).style = "display:none;";
}
}
function button_Click() {
if (document.getElementById("name")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
if (document.getElementById("email")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
}
I need the error displayed when someone tries to leave the name field empty and goes to the next text field (email).

Categories