form validation with data ranges - javascript

I am trying to validate HTML form. check a field with two other relative range fields. I want to check all variables isset and between the range before submitting form.
I tried this method not giving the expected result.
How can I do it with other easiest method.
$("#form").submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var apple = $('.apple').val();
var aFirst = $('.aFirst').val();
var aLast = $('.aLast').val();
var banana = $('.banana').val();
var bFirst = $('.bFirst').val();
var bLast = $('.bLast').val();
var orange = $('.orange').val();
var oFirst = $('.oFirst').val();
var oLast = $('.oLast').val();
if(apple >= aFirst && apple <= aLast){
var a = 'true';
}else{
var a = 'false';
}
if(banana >= bFirst && banana <= bLast){
var b = 'true';
}else{
var b = 'false';
}
if(orange >= oFirst && orange <= oLast){
var o = 'true';
}else{
var o = 'false';
}
if(a == 'true' && b == 'true' && o == 'true')
{
alert('success');
//do ajax
}else{
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Apple Price:</label>
<input type="number" class="apple" placeholder="Type between 15-25">
<input type="hidden" class="aFirst" value="10">
<input type="hidden" class="aLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>

The hidden input classes for apples should be aFirst and aLast:
Update: I have corrected the following line:
<input type="hidden" class="aLast" value="25">
Update 2: Works when fruit divs are removed. + Cleanup.
$("#form").submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var apple = $('.apple').val();
var aFirst = $('.aFirst').val();
var aLast = $('.aLast').val();
var banana = $('.banana').val();
var bFirst = $('.bFirst').val();
var bLast = $('.bLast').val();
var orange = $('.orange').val();
var oFirst = $('.oFirst').val();
var oLast = $('.oLast').val();
var a = true;
var b = true;
var o = true;
if (apple == "" || apple < aFirst || apple > aLast) {
a = false;
}
if (banana == "" || banana < bFirst || banana > bLast) {
b = false;
}
if (orange == "" || orange < oFirst || orange > oLast) {
o = false;
}
if (a && b && o) {
alert('success');
//do ajax
} else {
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>

There is a typo,
you have a class name as qFirst and qLast in HTML and js you have written .aFirst and .aLast.
Also convert all values to Number.
When you do .val(), it returns string. And Comparing Strings can give unexpected results
$("#form").submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var apple = Number($('.apple').val());
var aFirst = Number($('.aFirst').val());
var aLast = Number($('.aLast').val());
var banana = Number($('.banana').val());
var bFirst = Number($('.bFirst').val());
var bLast = Number($('.bLast').val());
var orange = Number($('.orange').val());
var oFirst = Number($('.oFirst').val());
var oLast = Number($('.oLast').val());
if(apple >= aFirst && apple <= aLast){
var a = 'true';
}else{
var a = 'false';
}
if(banana >= bFirst && banana <= bLast){
var b = 'true';
}else{
var b = 'false';
}
if(orange >= oFirst && orange <= oLast){
var o = 'true';
}else{
var o = 'false';
}
if(a == 'true' && b == 'true' && o == 'true')
{
alert('success');
//do ajax
}else{
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Apple Price:</label>
<input type="number" class="apple" placeholder="Type between 15-25">
<input type="hidden" class="aFirst" value="10">
<input type="hidden" class="aLast" value="25">
</div>
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>

Related

How to calculate discount for price and clear form when radio button is changed

1) I am trying to calculate discount for price with this code but it does not work.
2) I want to clear form when the radio button is changed. Example the size is M and fill number in quantity input only If I change the size, the form will be clear or after amount show me If I change size, the form will be clear too.
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', total)
});
var total = function () {
var s = Number(document.querySelector('input[name=size]:checked').value);
var q = Number(document.getElementById('qty').value);
var m = document.querySelector('input[name=member]:checked').value;
var result;
if(s && q && m) {
if(q >= 1) {
if(s == 'S') {
result = s * q;
} else if(s == 'M') {
result = s * q;
} else if(s == 'L') {
result = s * q;
} else {
result = s * q;
}
result -= m === "YES" ? result*5/100 : 0;
} else {
result = " ";
}
} else {
result = " ";
}
document.getElementById('amount').innerHTML = result.toFixed(2);
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
<form id="myForm">
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="text" name="qty" id="qty">
</p>
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
Your calculations are working as expected.
You have one problem in your Code:
document.getElementById('amount').innerHTML = result.toFixed(2); //Here with innerHTML
inputs cannot contain html. They can only contain a value. The property innerHTML is not ideal for input elements. What you are looking for is:
document.getElementById('amount').value = result.toFixed(2);
You must set the value of your amount, not innerHTML.
I have just edited your Snipped. Notice the changes I made on your code. A lot of stuff were unnecessary. Like your multiple if statements checking for 'S', 'M' ... Because at the end they all lead to the same calculation expression.
window.addEventListener("load", () => {
// clear then textboxes on Size change
document.querySelectorAll("input[name=size]").forEach(input=>{
input.addEventListener('change', ()=>{
clearTextBoxes();
});
});
});
var computeTotal = () =>
{
var s = document.querySelector('input[name=size]:checked').value;
var q = document.getElementById('qty').value;
var m = document.querySelector('input[name=member]:checked').value;
var result; //initialize to empty string
if(s && q && m && q >= 1) {
result = s * q;
result -= m === "YES" ? result*5/100 : 0;
}
// Change innerHTML to value
document.getElementById('amount').value = result == undefined ? " " : result.toFixed(2);
}
var clearTextBoxes = () => {
document.getElementById("qty").value = "";
document.getElementById("amount").value = "";
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
<form id="myForm">
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="number" name="qty" id="qty">
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate" onclick="computeTotal()">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
You need to clear the input fields when radio button changes. Find the working demo below
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', total)
});
var total = function() {
var s = Number(document.querySelector('input[name=size]:checked').value);
var q = Number(document.getElementById('qty').value);
var m = document.querySelector('input[name=member]:checked').value;
var result;
if (s && q && m) {
if (q >= 1) {
if (s == 'S') {
result = s * q;
} else if (s == 'M') {
result = s * q;
} else if (s == 'L') {
result = s * q;
} else {
result = s * q;
}
result -= m === "YES" ? result * 5 / 100 : 0;
} else {
result = " ";
}
} else {
result = " ";
}
document.getElementById('amount').value = result.toFixed(2);
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
// Add event listener to all radio items and add the clearfields logic
var memberRadios = document.querySelectorAll('input[type=radio][name="member"]');
var sizeRadios = document.querySelectorAll('input[type=radio][name="size"]');
Array.prototype.forEach.call(memberRadios, function(radio) {
radio.addEventListener('change', clearFields);
});
Array.prototype.forEach.call(sizeRadios, function(radio) {
radio.addEventListener('change', clearFields);
});
function clearFields(event) {
document.getElementById('qty').value = null;
document.getElementById('amount').value = null;
}
<form id="myForm">
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="text" name="qty" id="qty">
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>

Action attribute not working on JS validated form

The files are in the the correct locations, both the form page and form complete page are in the same folder. When I click submit, it validates the form correctly, but if everything is entered correctly and validates, it does nothing, just takes away the asterisks like it's supposed to in the js. I want it to link to the form_complete.html page after you hit submit and the validation runs, but after it validates nothing happens,
The html:
<form id="contactform" action="form_complete.html" method="post">
<p class = "labelp">
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Enter your name" >
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="age">Age: </label>
<input type="text" min="18" max="100" name="age" id="age" placeholder="Enter your age">
<!-- using type=text so I can practice isNaN in js -->
<span>*</span><br><br>
</p>
<p class = "labelp"></p>
<label for="country">Country: </label>
<select name="country" id="country">
<option value ="">Select a country</option>
<option>USA</option>
<option>Canada</option>
<option>Mexico</option>
<option>Brazil</option>
<option>Japan</option>
<option>China</option>
<option>Other</option>
</select>
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="email">E-mail: </label>
<input type="email" name="email" id="email" placeholder="Enter your E-mail">
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="bday">Birthday: </label>
<input type="date" name="bday" id="bday">
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="gender" id="gender">Gender: </label>
<input type="radio" name="gender" value="male" id="male"> Male
<input type="radio" name="gender" value="female" id="female"> Female
<input type="radio" name="gender" value="other" id="other"> Other
<br><br>
</p>
<label>Comments: </label>
<textarea rows="5" cols="30"> </textarea><br><br>
<input type="button" id="registerbtn" value="Submit">
<input type="button" id="resetbtn" value="Reset">
</form>
The javascript:
"use strict";
var $ = function(id) { return document.getElementById(id);};
var processEntries = function(){
var isValid = true;
// values
var name = $("name").value;
var age = $("age").value;
var country = $("country").value;
var email = $("email").value;
var bday = $("bday").value;
var gender = "";
if ($("male").checked){gender = "Male";}
if ($("female").checked){gender = "Female";}
if ($("other").checked){gender = "Other";}
console.log(gender); //check if gender buttons work
// name
if(name == ""){
$("name").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("name").nextElementSibling.firstChild.nodeValue = "";
}
// age
if(age == ""){
$("age").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;
}
else if(isNaN(age)){
$("age").nextElementSibling.firstChild.nodeValue = "This field must be a number!";
isValid = false;
}
else{
$("age").nextElementSibling.firstChild.nodeValue = "";
}
//country
if(country == ""){
$("country").nextElementSibling.firstChild.nodeValue = "Please select a country!";
isValid = false;}
else{
$("country").nextElementSibling.firstChild.nodeValue = "";
}
//email
if(email == ""){
$("email").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("email").nextElementSibling.firstChild.nodeValue = "";
}
//birthday
if(bday == ""){
$("bday").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("bday").nextElementSibling.firstChild.nodeValue = "";
}
}
var resetForm = function(){
$("contactform").reset();
$("name").nextElementSibling.firstChild.nodeValue = "*";
$("age").nextElementSibling.firstChild.nodeValue = "*";
$("country").nextElementSibling.firstChild.nodeValue = "*";
$("email").nextElementSibling.firstChild.nodeValue = "*";
$("bday").nextElementSibling.firstChild.nodeValue = "*";
}
window.onload = function() {
$("registerbtn").onclick = processEntries;
$("resetbtn").onclick = resetForm;
$("name").focus();
}
Please put below condition at the end of "processEntries" function
if(isValid){
$("#contactform").submit();
}

Simple js calculator with radio tag

I found subjects like mine but I could not fix my problem. So I wanted to calculate the cost of tickets form radio tags by multiplying the price with the amount of tickets using if statements for each option without jquery. I can not figure it out why I do not have an output. It looks like none of my functions work and I can not find why.
Can you help me please, I know it is easy but I am still a beginner
<!doctype html>
<html>
<head>
<title>No Boundaries</title>
<link rel="stylesheet" href="styles1.css">
<script type="text/javascript">
function validate(){
if(!document.form1.cond.checked)
{alert("Please accept the Terms and Conditions");
return false;
}
if(document.form1.name.value.length < 2)
{alert(“Please enter your full name, not just an initial”);
return false;
}
return true;
}
function cost() {
if (document.form1.accom["v"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom["t"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom["c"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
function post(){
if(document.form1.del["1"].checked){
var num = 0;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["2"].checked){
var num = 12;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["3"].checked){
var num = 16;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["4"].checked){
var num = 20;
var ans = num;
document.form1.total2.value = ans;
}
}
function damage(){
var total1 = parseInt(document.form1.total1.value);
var total1 = parseInt(document.form1.total1.value);
var ans = total1 + total2;
document.form.total3.value = ans;
}
</script>
</head>
<body>
<section>
<form name="form1">
<fieldset>
<legend>Personal details</legend>
<div>
Please enter your full name<br>
<input name="name" type="text" required onsubmit="return validate();"><br>
</div>
<div>
Address<br>
<input name="addresss" type="text" required><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
</div>
<div>
Phone Number<br>
<input name="phone" type="tel"><br>
</div>
<div>
Email Address<br>
<input name="email" type="email" required><br>
</div>
<div>
Date of Birth<br>
<input name="birth" type="date"><br>
</div>
</fieldset>
<fieldset>
<legend>Ticket Details</legend>
<div>
Type of T<br>
<label for="vil">V</label>
<input type="radio" name="accom[]" value="v">
<label for="town">T</label>
<input type="radio" name="accom[]" value="t">
<label for="con">C</label>
<input type="radio" name="accom[]" value="c">
</div>
<div>
Quantity of T
<input name="amount" type="number" min="1" max="10" required><br>
<br>
<input type="button" name="cost" value="C C" onclick="cost();"><br>
</div>
<div>
Delivery Options<br>
<input type="radio" name="del[]" value="1" >Free<br>
<input type="radio" name="del[]" value="2" >£12<br>
<input type="radio" name="del[]" value="3" >£16<br>
<input type="radio" name="del[]" value="4" >£20<br>
<br>
<input type="button" value="C D" onclick="post();"><br>
</div>
</fieldset>
<fieldset>
<legend>Terms And Conditions</legend>
<input name="cond" type="checkbox" onsubmit="return validate();">
</fieldset>
<fieldset>
<legend>Cost</legend>
<input type="text" name="total1" readonly><br>
<input type="text" name="total2" readonly><br>
<input type="text" name="total3" readonly><br>
<br>
<input type="button" value="C F C" onclick="damage();"><br>
</fieldset>
<br><br>
<fieldset>
<input type="submit">
</fieldset>
</form>
</section>
</body>
</html>
the cost function should be something like this,
function cost() {
if (document.form1.accom.value.toLowerCase() == "v") {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
} else if (document.form1.accom.value.toLowerCase() == "t") {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
} else if (document.form1.accom.value.toLowerCase() == "c") {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
And to make the code more refactored, make it like this,
function cost() {
var val = document.form1.accom.value.toLowerCase();
var amount = parseInt(document.form1.amount.value);
var ans;
if (val == "v") {
ans = 90 * amount;
} else if (val == "t") {
ans = 150 * amount;
} else if (val == "c") {
ans = 45 * amount;
}
document.form1.total1.value = ans;
}
Ok I found your errors. This is the code for html
<div>
Type of T<br>
<label for="vil">V</label>
<input type="radio" name="accom" value="v">
<label for="town">T</label>
<input type="radio" name="accom" value="t">
<label for="con">C</label>
</div>
<div>
Quantity of T
<input name="amount" type="number" min="1" max="10" required><br>
<br>
<input type="button" name="cost" value="C C" onclick="costs();"><br>
</div>
Next, in your javascript you have tho change the name of function; instead of cost you have to renaming in costs
function costs() {
if (document.form1.accom.value == 'v') {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom.value == 't') {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.a`enter code here`ccom.value == 'c') {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
That's all

javascript: submit button pulls all values from the textboxes and displays them in a p tag

So what I am trying to do here is when the submit button is clicked pull all of the values from the textboxes and display them in a p tag that I have on my html page. I have been tring to figure this out for days. Can somebody let me know what I am doing wrong?
/* JavaScript */
$("#submit").click(function(){
var doc = $("#doctorate").val()
var Name = $("#first_name").val();
var Last = $("#last_name").val();
var T = Doc + " "+ Name + " " + Last
break
var Certs = $("#certs").val()
break
var Title = $("#title").val()
break
var Department = $("#department").val()
break
var Numb = $("#number").val()
break
var Web = $("#website").val()
break
var Ema = $("#email").val()
document.getElementById('output').innerHTML = T;
})
HTML unchanged
The big problem I see is that you keep assigning the same thing to your output. Try something like this (reduced for brevity):
function myOut() {
var output = document.getElementById("certs").value;
output = output + document.getElementById("title").value;
if (certs != null) {
document.getElementById("output").innerHTML = output;
}
}
<input type="text" id="certs" />
<input type="text" id="title" />
<p id="output"></p>
<button onclick="myOut()">
Sub
</button>
Here you can try this one.
var role = document.getElementById("role").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var doctorate = document.getElementById("doctorate").value;
var certs = document.getElementById("certs").value;
var title = document.getElementById("title").value;
var department = document.getElementById("department").value;
var number = document.getElementById("number").value;
var website = document.getElementById("website").value;
var email = document.getElementById("email").value;
var output = document.getElementById("output").value;
$("#submit").click(function(){
var N = $("#first_name").val();
var L = $("#last_name").val();
var T = N + " " + L;
if (doctorate.checked) {
document.getElementById('output').innerHTML = T;
}
if (first_name != null) {
document.getElementById('output').innerHTML = T;
}
if (last_name != null) {
document.getElementById('output').innerHTML = T;
}
if (certs != null) {
document.getElementById('output').innerHTML = T;
}
if (title != null) {
document.getElementById('output').innerHTML = T;
}
if (department != null) {
document.getElementById('output').innerHTML = T;
}
if (number != null) {
document.getElementById('output').innerHTML = T;
}
if (website != null) {
document.getElementById('output').innerHTML = T;
}
if (email != null) {
document.getElementById('output').innerHTML = T;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset id="role">
<legend>My Role</legend>
<label for="faculty">
<input type="radio" name="role" id="faculty" value="faculty" />
Faculty
</label>
<label for="staff">
<input type="radio" name="role" id="staff" value="staff" />
Staff
</label>
</fieldset>
<fieldset id="userinformation">
<legend>User Information</legend>
<label for="doctorate">
Doctorate?
<input type ="checkbox" id="doctorate" value="" />
</label>
<label>
First Name:
<input type="text" name="name" id="first_name" required />
</label>
<label>
Last Name:
<input type="text" name="name" id="last_name" required />
</label>
<label>
Certifications:
<input type="text" name="cert" id="certs" />
</label>
<label>
Title:
<input type="text" name="title" id="title" required />
</label>
<label>
Department:
<select id="department" required>
<option disabled selected value>-Select a Department-</option>
<option>School of Information Technology</option>
<option>Mathematics</option>
<option>English</option>
<option>History</option>
<option>Natural Sciences</option>
<option>Psychology</option>
<option>School of Health Sciences</option>
</select>
</label>
<label>
Primary Phone #:
<input type="tel" name="number" id="number" placeholder="444-123-1234" pattern="^\d{3}-\d{3}-\d{4}$"/>
</label>
<label>
Email:
<input type="email" name="email" id="email" placeholder="JDoe#example.com" required />
<span id="err3"></span>
</label>
<label>
Website:
<input type="text" name="website" id="website" placeholder="http//:www.example" pattern="https?://.+" />
</label>
</fieldset>
<fieldset id = "results">
<p id="output"></p>
</fieldset>
<fieldset id="submit_button">
<input type="button" id="submit" value="submit" />
</fieldset>

Javascript form verification for this

I need to do a Javascript verification of the fields. I need to know how to make for each span of every label how to make it display the write message.
At the moment the html code is:
<form method="post" id="contactForm" onclick="return main();">
<fieldset>
<div class="subscribe">
<label for="firstName">First name:</label>
<input type="text" name="firstName" id="firstName"/>
<span id="fnameMessage" class="infomessage">
Your first name should contain at least 2 alpha characters.
</span>
</div>
<div class="subscribe">
<label for="lastName">Last name:</label>
<input type="text" name="lastName" id="lastName"/>
<span id="lnameMessage" class="infomessage">
Your last name should contain at least 2 alpha characters.
</span>
</div>
<div class="subscribe">
<label for="title">Title:</label>
<select name="title" id="title">
<option value="1"> Mr. </option>
<option value="2"> Ms. </option>
<option value="3"> Mrs. </option>
<option value="4"> Miss. </option>
<option value="5"> Master. </option>
</select>
</div>
<div class="subscribe">
<label for="hNumber">Health Authority Number:</label>
<input type="text" name="number" id="hNumber"/>
<span id="hanMessage" class="infomessage">
Your ZHA number should be in the form of 6 digit integer prefixed wit the letters ZHA.
</span>
</div>
<div class="subscribe">
<label for="email">Email address: </label>
<input type="email" name="email" id="email"/>
<span id="emailMessage" class="infomessage">
Your email address should be as example: example#difexample.com.
</span>
</div>
<div class="subscribe">
<label for="phoneNumber">Telephone number:</label>
<input type="text" name="phoneNumber" id="phoneNumber"/>
<span id="phoneMessage" class="infomessage">
Your phone number should contain 11 numeric characters.
</span>
</div>
<div class="button">
<input id="btn1" type="submit" value="Submit" />
</div>
</fieldsed>
</form>
The javascript code that I've done it's:
function main() {
document.getElementById("contactForm").onsubmit = validateAll,
document.getElementById("firstName").onblur = validateName,
document.getElementById("lastName").onblur = validateName,
document.getElementById("phoneNumber").onblur = validatePhone;
}
function validateName() {
var test1 = fieldEmpty(this);
var test2 = fieldLength(this,2,50);
var test3 = fieldCharacters(this, "A");
var result = test1&&test2&&test3;
return result;
}
function validatePhone() {
var test1 = fieldEmpty(this);
var test2 = fieldLength(this,11,11);
var test3 = fieldCharacters(this,"N");
var result = test1&&test2&&test3;
return result;
}
function fieldEmpty(id) {
var valid = true;
if (id.value == "") {
valid = false;
alert("Field Empty");
}
return valid;
}
function fieldLength(id,min,max) {
var valid = true;
var lng = id.value.length;
if (lng < min || lng > max) {
valid = false;
alert("Field Length");
}
return valid;
}
function fieldCharacters(id,character) {
var letters = /[a-zA-Z]/;
var numbers = /[0-9]/;
var patternTest;
var valid = true;
if(character == "N") {
patternTest = numbers;
}
else if(character == "A") {
patternTest = letters;
}
valid = patternTest.test(id.value);
if (!valid) {
alert("Pattern Fail");
}
return valid;
}
function validateField() {
var noErrors = true;
// var input = document.getElementById(this);
if(this.value.length<2) {
noErrors = false;
alert("You need to input more than 1 character in " + this.id);
}
if(noErrors==false) {
var temp = document.getElementById(this.id + "firstnamemessage");
temp.className = "infomessage";
}
}
function validateAll() {
return false;
}
window.onload = main();

Categories