Trying to create a form with pretty simple validation and I'm curious as to two things.
One; how do I check if a form is empty?
Two; on the phone number field how would I only accept numbers in this format:
xxx-xxxx (where X is a number)
Here is what I have done so far:
HTML:
<form onsubmit="return false" method="post" name="myForm">
<div class="form-block">
<label>Name: </label>
<input type="text" name="name" id="name" />
<span id="name-error" class="error"></span>
</div>
<div class="form-block">
<label>Phone Number: </label>
<input type="text" name="phone" id="phone" />
<span id="phone-error" class="error"></span>
</div>
<input type="submit" id="mysubmit" name="submit" onclick="validate()" />
</form>
CSS:
a, p, h1, h2, h3, h4, h5, h6, li, label, span {
font-family: sans-serif;
}
#mysubmit {
display: block;
margin-top: 10px;
}
span.error {
color: red;
font-weight: bold;
}
.form-block {
display: block;
width: 100%;
margin: 10px 0;
}
label {
display: inline-block;
width: 150px;
text-align: right;
}
JS:
validate = function() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
if(/^[a-zA-Z]*$/.test(name)) {
document.getElementById("name-error").innerHTML = "Good.";
} else {
document.getElementById("name-error").innerHTML = "Invalid. Only letters.";
}
if(isNaN(phone)) {
document.getElementById("phone-error").innerHTML = "Can only contain numbers";
} else {
document.getElementById("phone-error").innerHTML = "Good.";
}
};
You can test if the value of a form element is empty by simply checking for an empty string.
I've already posted something that will help you access and iterate through form fields.
// ES5: a very crude validation check
// your form field elements should share a class in order to collect them all
var formElements = document.querySelectorAll('.your-form-field-class');
// set a flag to keep track of whether you have an empty field
var containsEmptyField = false
i,
l = formElements.length;
for (; i < l; i++) {
if (formElements[i].value === '') {
containsEmptyField = true;
// do something in response to an empty field
// the break is to stop looping since you've found
// a match
break;
}
}
// ES6: a very crude validation check
const formElements = document.querySelector('#some-form').elements;
let containsEmptyField = false;
for (let element of formElements) {
if (element.value === '') {
containsEmptyField = true;
break;
}
}
I haven't tested it properly, but the regex for the phone number, might look something like this:
(/^(\d){3,3}\-(\d){4,4}$/).test(someNumber)
// returns true if value matches or false if it doesn't
Related
I am trying to convert a Python script into an HTML/Javascript web based converter. The script is very simple and I followed the steps at https://www.w3schools.com/howto/howto_js_length_converter.asp, which work great, if all fields are dynamic. In my case, I need one variable to not change. On an example: user provides the "AssayWeight" value and one of the following: PPM or Grav. After that, scripts calculates the other value from PPM/Grav that the user didn't provide. Here's the code I have so far:
<script>
function ppmtoGravConverter(source,valNum) {
valNum = parseFloat(valNum);
var inputPPMtoGrav = document.getElementById("inputPPMtoGrav");
var inputAssayWeight = document.getElementById("inputAssayWeight");
var inputGravtoPPM = document.getElementById("inputGravtoPPM");
if (source=="inputPPMtoGrav") {
inputGravtoPPM.value=(valNum*inputAssayWeight/1000).toFixed(4);
}
if (source=="inputGravtoPPM") {
inputPPMtoGrav.value=(valNum*1000/inputAssayWeight).toFixed(4);
}
}
</script>
and html from w3schools:
<label>Assay Weight</label>
<input id="inputAssayWeight" type="number" placeholder="Assay Weight" oninput="ppmtoGravConverter(this.id,this.value)" onchange="ppmtoGravConverter(this.id,this.value)">
<br><br>
<label>PPM</label>
<input id="inputPPMtoGrav" type="number" placeholder="PPM" oninput="ppmtoGravConverter(this.id,this.value)" onchange="ppmtoGravConverter(this.id,this.value)">
<label>Grav (mg)</label>
<input id="inputGravtoPPM" type="number" placeholder="Grav (mg)" oninput="ppmtoGravConverter(this.id,this.value)" onchange="ppmtoGravConverter(this.id,this.value)">
Please let me know what am I missing. This is my 2nd day looking at Javascript. Thanks!
The issue is that in your formula, you are using inputAssayWeight instead of actually taking its value and using it. Replace those two if conditions with
if (source=="inputPPMtoGrav") {
inputGravtoPPM.value=(valNum*parseFloat(inputAssayWeight.value)/1000).toFixed(4);
}
if (source=="inputGravtoPPM") {
inputPPMtoGrav.value=(valNum*1000/parseFloat(inputAssayWeight.value)).toFixed(4);
}
That should fix your issue.
Wrap everything in a <form> tag and give it an #id.
<form id='main'><!-- EVERYTHING --></form>
Bind "input" event to the <form> and call an event handler (i.e. a function to handle a triggered event). Refer to: JavaScript Event Handling
document.forms.main.oninput = inputHandler;
Define function inputHandler() -- remember to pass the Event Object
function inputHandler(event) {...
Define all variables -- refer to: Obtaining References to Forms and Form Elements in JavaScript
// Collect all form controls into a NodeList
const field = this.elements;
// Find the element user interacted with
const input = event.target;
// Reference any form control by #id or [name] attribute by prefixing it with `field`
const aW = field.assayWeight;
// Assign a variable to form control values and convert them into a real Number
let AWT = parseFloat(aW.value);
Delegate "input" event by using if/else flow control statements. By explicitly allowing specific elements to react to an event and implicitly preventing other elements by simple omission is an important part of a programming paradigm called Event Delegation.
if (input.matches('#assayWeight')) {...
The HTML/CSS layout and styling features a toggling system in which it allows the user to enter "assay weight" and either "PPM" or "Grav". Hover over the titles and then click one and then the other to see the toggling. Refer to: Exposing Form Fields Via Checked Radio Buttons
[name=conv],
.mask {
display: none
}
[name=conv]:checked + fieldset .mask {
display: inline-block;
}
Demo
document.forms.convPpmG.oninput = convert;
function convert(event) {
const field = this.elements;
const input = event.target;
const awt = field.aWt;
const ppm = field.pPM;
const grv = field.grv;
const gtp = field.gToP;
const ptg = field.pToG;
let AWT = parseFloat(awt.value);
let PPMin = parseFloat(ppm.value);
let GRVin = parseFloat(grv.value);
if (input.matches('#aWt')) {
// log(AWT, "Assay Weight");
}
if (input.matches('#pPM')) {
// log(PPMin, "PPM Input");
let GRVout = PPMin * AWT / 1000;
// log(GRVout, "Grav Output");
ptg.value = GRVout.toFixed(4);
}
if (input.matches('#grv')) {
// log(GRVin, "Grav Input");
let PPMout = GRVin * 1000 / AWT;
// log(PPMout, "PPM Output");
gtp.value = PPMout.toFixed(4);
}
}
// A utility logger - not required
const log = (data, key = 'Field') => console.log(JSON.stringify(key + ': ' + data));
root,
body {
font: 400 3vw/1.5 Consolas, monospace;
}
fieldset fieldset {
min-height: 20vh;
}
input,
output {
width: 10ch;
margin-right: 5px;
margin-bottom: 8px;
font: inherit;
text-align: right;
}
#aWt {
display: inline-block;
}
[type=reset] {
text-align: center;
}
.switch {
padding: 3px 5px;
}
[type=reset]:hover,
.switch:hover {
color: tomato;
background: rgba(56, 87, 199, 0.4);
cursor: pointer;
}
[name=conv],
.mask {
display: none
}
[name=conv]:checked+fieldset .mask {
display: inline-block;
}
<form id='convPpmG'>
<fieldset>
<legend>PPM / Grav Convertor</legend>
<label>Assay Weight</label>
<input id="aWt" type="number" min='0' value="0">
<input type='reset'>
<br>
<input id='ppmToGrav' name='conv' type='radio'>
<fieldset>
<legend>
<label for='ppmToGrav' class='switch'>PPM to Grav</label>
</legend>
<label class='mask'>
PPM: <input id="pPM" type="number" min='0' value="0">
to Grav: <output id='pToG'>0</output> mg
</label>
</fieldset>
<hr>
<input id='gravToPPM' name='conv' type='radio'>
<fieldset>
<legend>
<label for='gravToPPM' class='switch'>Grav to PPM</label>
</legend>
<label class='mask'>
Grav: <input id="grv" type="number" min='0' value="0">
mg to PPM: <output id='gToP'>0</output>
</label>
</fieldset>
</fieldset>
</form>
I working on Javascript validation task as i am beginner in Javascript i was stuck in Js validation code codepen.Can, Anyone Please help out of this and point me in right direction.
Thanks in advance.
jQuery(document).ready(function($) {
function formValidation() {
var firstname = document.getElementById('product');
if (firstname.value.length == 0) {
document.getElementById('head').innerText = "* All fields are mandatory *";
firstname.focus();
return false;
}
if (inputAlphabet(firstname, "* For your name please use alphabets only *")) {
return true;
}
return false;
}
function textNumeric(inputtext, alertMsg) {
var numericExpression = /^[0-9]+$/;
if (inputtext.value.match(numericExpression)) {
return true;
}
else {
document.getElementByClass('price').innerText = alertMsg;
inputtext.focus();
return false;
}
}
function inputAlphabet(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
}
else {
document.getElementById('product').innerText = alertMsg;
inputtext.focus();
return false;
}
}
});
body {
background: #f5f5f5;
}
.product-container {
display: flex;
justify-content: center;
align-items: center;
padding: 100px;
}
input#product {
max-width: 200px;
padding: 5px 20px;
}
input.price {
max-width: 227px;
padding: 5px 4px;
width: 100%;
}
input.qnty {
max-width: 235px;
width: 100%;
padding: 5px 4px;
}
input[type="submit"] {
font-size: 14px;
font-family: 'Roboto', sans-serif;
font-weight: 500;
color: #000000;
padding: 5px 10px;
letter-spacing: 0.6px;
}
<!DOCTYPE html>
<html>
<head>
<title>Product Order</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="custom.js"></script>
</head>
<body>
<div class="product-container">
<form action="submit" method="POST">
Product Name: <input type="text" name="name" value="" required id="product" ><br><br>
Unit Price: <input type="number" name="Price" value= "" required class="price" pattern="\d+(\.\d{2})?"><br><br>
Quantity: <input type="number" name="Quantity" value="" min="1" max="10" required class="qnty price"><br><br>
<input type = "submit" name = "submit" value = "Get Total Amount">
</form>
</div>
</body>
</html>
You're doing the same thing I was doing when I started using jQuery... mixing JavaScript with jQuery.
You don't need to create a function to validate the form. I'd first change your submit button to this:
<button type="button" id="submitButton">Submit</button>
Then use jQuery to listen for the button click:
$('#submitButton').on('click', function() {
var product = $('#product').val();
var price = $('.price').val();
var name = $('#name').val();
// check if name input has a value, if blank, then display error message
if(name == "") {
alert('You must enter a name');
return false;
}
if(product == '//whatever you want to check here') {
// display message
}
if(price == '// check if the input is blank') {
// return error message
}
else {
// do something
}
});
The if/else inside your button click is your validation.
I see a ton of errors in your very small code. Your Jquery code looks very bad. You are creating functions but never using them, You don't have to create functions for form validation. You can use Jquery event listeners to check if the user has performed some action like (submit, Focus, Blur etc.,) and when you receive the event you have to perform an action and clearly innerText does not work on input boxes. Go through this article on form validation using Jquery.
You should do basic google search before posting a question here.
The code below obviously has a lot of errors or some other things missing but I am beginner to JavaScript trying to make my own projects.
I tried to make this contact form with JavaScript validation from my own and a bit with a search but I'm stuck because validation form doesn't work at all. I would appreciate if you help me fixing this, thank you.
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
function validateName() {
if (name === null) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name < characters.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
if (email === null) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email < characters.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name">
<br>
<input class="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Well, you only defined validation methods but don't use them, that's why they have no effect.
You should add event listeners like onchange (or oninput, depending on when you'd like to show error messages) to your fields.
For instance:
<input class="name" type="text" placeholder="Your Name" onchange="validateName()">
Actually, you have multiple more problems:
error is undefined: you should create another element and find it in JS
you have to use element.value, not element to access a value of input
you have undefined characters used in a weird way in your checks; to check the length of content, use element.value.length
Here's a snippet with these fixes:
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
let error = document.querySelector('.error');
function validateName() {
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name" onchange="validateName()">
<br>
<input class="email" type="email" placeholder="Your Email" onchange="validateEmail()">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<div class="error"></div>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Moreover, I'd make some more improvements to the code, namely
use event.target inside event handlers instead of calcing the elements globally (note the difference in usage inside html too);
clear the error div when the content is ok!
why multiple return false instead of one in the end of the handler?
you don't use the submit variable, get rid of it; does submitForm do anything useful? (submits on submit??) Not sure, but it seems it should be removed, too
let error = document.querySelector('.error');
function validateName(event) {
let name = event.target;
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
} else {
error.innerHTML = '';
}
return false;
}
function validateEmail(event) {
let email = event.target;
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
} else {
error.innerHTML = '';
}
return false;
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name" onchange="validateName(event)">
<br>
<input class="email" type="email" placeholder="Your Email" onchange="validateEmail(event)">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<div class="error"></div>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Alot of your syntax and validation methods are off. Few tips: you need to use name.value and email.value to get the values of the elements, you also need to use name.value.length instead of email < characters.length < 5 and change the button type to submit and you can negate having to call it in JS.
Below is a working snippet based on the code you posted. I believe it does what you want.
let error = document.getElementById('error');
function validateName() {
let name = document.getElementById('name');
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters on name';
return false;
}
}
function validateEmail() {
let email = document.getElementById('email');
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 5 characters on email';
return false;
}
}
function submitForm() {
error.innerHTML = ""
validateEmail()
validateName()
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input id="name" type="text" placeholder="Your Name">
<br>
<input id="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" type = "submit" action="/submit.php" onclick="submitForm()">Submit</button>
<div id="error">
</div>
</div>
</div>
You've written your JS function validateName and validateEmails but you aren't calling those functions anywhere. Instead of selecting the .submit button inside of submitForm(), call those functions. The line you have inside of submitForm is doing nothing. onclick() within your HTML handles the calling of the function submitForm(), and submitForm() should then validate your form.
Edit: you can also call validateName and validateEmails when the email or name fields are edited.
Yeah, like what the other contributors said, the validate functions are written well, they just aren't being called.
You can either add them to the onchange property of your input elements, or call it in your submitform function like so:
function validateName() {
if (name === null) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name < characters.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
return true;
}
function validateEmail() {
if (email === null) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email < characters.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
return true;
}
function submitForm(){
if(validateName() && validateEmail()){
//Do whatever submitting entails
}
}
Also remember to add an error div to your html to display the errors, and to create an error querySelector variable like you did with name, email and submit.
You're doing great! Keep up the good work!
Here's something that works to a minimum using your current code. I added comments to explain what is going on. Don't hesitate to ask me for any clarifications. Like you said, code can be improved further but I didn't want to change too much and confuse you.
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
let error = document.querySelector('#error'); //Get's the span in the html where the errors will be shown.
function validateName() {
//Get the text value of name with name.value and care with an empty string.
if (name.value === "") {
error.innerHTML = 'Name cannot be blank';
return false;
//Get the number of character in the value of the name and see if you have less than 3.
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
//Get the text value of name with name.value and compare with an empty string.
if (email.value === "") {
error.innerHTML = 'Email cannot be blank';
return false;
//Get the number of characters in the value of the email and see if you have less than 5.
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
//Instead of calling the function .submit (that doesn't exist). Call the verification functions that you made.
validateName();
validateEmail();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<span id="error"></span>
<input class="name" type="text" placeholder="Your Name">
<br>
<input class="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
I am trying to figure out why the form's "submit this form" button is not taking me to another HTML page I specified in the <form ... action="submit form.html" method="get"> attribute and not only that but when I put wrong first names, email addresses, and order numbers, and date of orders, it doesn't return JavaScript messages I specified in my if-else codes using JavaScript.
Here is the JavaScript code I use on the form.
var $ = function (id)
{
return document.getElementById(id);
}
var submitForm = function()
{
var FirstName= $("firstName").value;
var OrderNumber= $("orderNumber").value;
var DateOfOrder= $("date_of_order").value;
var emailAddress= $("email_address").value;
var isValid=true;
if(FirstName !== "Cherry", "Micheal", "Sandra", "Cookie")
{
$("firstname_error").firstChild.nodeValue=
"This person does not exist.";
isValid=false;
} else{ $("firstname_error").firstChild.nodeValue="";}
if(OrderNumber !== 3134, 4234, 9234, 3566)
{
$("orderNumber_error").firstChild.nodeValue="Invalid Order Number.";
isValid=false;
} else{ $("orderNumber_error").firstChild.nodeValue="";}
if(DateOfOrder !=='12-07-23', '15-04-24', '16-02-01', '14-01-12')
{
$("date_of_order_error").firstChild.nodeValue="Date doesn't exist in
system";
isValid=false;
} else{ $("date_of_order_error").firstChild.nodeValue="";}
if(emailAddress !="cherryjackson#gmail.com", "michealroberts#yahoo.com",
"sandrabell#hotmail.com", "cookiedanny#outlook.com")
{
$("email_address_error").firstChild.nodeValue="The email doesn't exist";
isValid=false;
} else{ $("email_address_error").firstChild.nodeValue="";}
if(isValid)
{
//submit the form if all entries are valid
$("cookie_form").submit();
}
}
window.onload = function()
{
$("form_submission").onclick = submitForm;
$("email_address").focus();
}
body{
background-color:#FBFBE8;
}
/* Tells HTML5 to find the font-type-face that my OS has and then use that for heading 1
and also centers the first heading */
h1{
font-family:Arial, Helvetica, sans-serif;
text-align:center;
}
/* Tells HTML5 to use any of the font-types for my first paragraph in HTML source file
if one is not available. Also clears some white space
from the left margin of the paragraph and finally tells it to give that paragraph
a size of 20 pixels. */
p{
font-family:Arial, Helvetica, sans-serif;
padding: 20px;
font-size:20px;
}
label{
float: left;
width: 11em;
text-align: right;
font-family:Arial, Helvetica, sans-serif;
color:#800000;
}
input{
margin-left: 1em;
margin-bottom:.5em;
}
span{
color: red;
}
.field_set_1{
border-color: purple;
border-style: solid;
}
#form_submission{
background-color:black; color:white;
}
legend{
font-family:Arial, Helvetica, sans-serif;
color:blue;
}
/* All of the classes are just for positioning and floating the four
same images around the form input information */
.Wrap1{
float:right;
margin:40px;
width:200px;
height:200px;
}
.Wrap2{
float:left;
margin:40px;
width:200px;
height:200px;
}
.clearfix {
clear: both;
}
<!DOCTYPE html>
<html>
<head>
<title>Cookie Order Form </title>
<link rel="stylesheet" href="First_Design.css">
<script src="cookieform.js"></script>
</head>
<body>
<h1>Cookie Order Form</h1>
<p>This form is a cookie order form for customers that purchased cookies from
Daron's Cookies Company and the following below must be filled out in order for each
customer to receive a final message that tells them when their order will be ready.</p>
<IMG class="Wrap1" SRC="cookie.gif" alt="cookie">
<IMG class="Wrap2" SRC="cookie.gif" alt="cookie2">
<!--The customer will be sent to the HTML page named "submit form.html" after they
click the "Submit this Form" button. The code below does this. -->
<div>
<form id="cookie_form" name="cookie_form" action="submit form.html" method="get">
<fieldset class="field_set_1">
<!-- Below sets the title of the form-->
<legend>Customer Order Form Information:</legend>
<!-- Creates the first left label to specify what should be placed in the text box
the the right of the label. The rest below does the same.-->
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName">
<span id="firstname_error">*</span><br>
<label for="orderNumber">Order Number:</label>
<input type="text" id="orderNumber" name="orderNumber">
<span id="orderNumber_error">*</span><br>
<label for="date_of_order">Date of Order:</label>
<input type="text" id="date_of_order" name="date_of_order">
<span id="date_of_order_error">*</span><br>
<label for="email_address">Email Address:</label>
<input type="text" id="email_address" name="email_address">
<span id="email_address_error">*</span><br>
<label> </label>
<input type="button" id="form_submission" value="Submit this Form">
</fieldset>
</form>
</div>
<div class="clearfix">
</div>
<IMG class="Wrap1" SRC="cookie.gif" alt="cookie">
<IMG class="Wrap2" SRC="cookie.gif" alt="cookie2">
</body>
</html>
There were a great many things wrong with your code, but the biggest was your validation tests, that each followed the same structure of:
if(FirstName !== "Cherry", "Micheal", "Sandra", "Cookie")
You can't test firstName against a comma-separated list of values. Each one must be tested individually and you must use a compound logical operator between them:
if(FirstName !== "Cherry" && FirstName !== "Micheal" &&
FirstName !== "Sandra" && FirstName !== "Cookie")
You were also using a standard button, rather than a submit button, which can cause all your validation to be bypassed in some situations when the ENTER key is hit. Always use a submit button and validate in the submit event.
Please see my restructured and re-organized code solution for inline comments.
The Stack Overflow snippet environment (below) doesn't work with forms
(because it's sandboxed), but the same code can be run here.
// W3C DOM Event model instead of node event properties:
window.addEventListener("DOMContentLoaded", function() {
// Since we're now using the submit event, we hook into that event:
// Use camelCase for JavaScript identifiers
var form = getElem("cookieForm");
form.addEventListener("submit", validate);
getElem("emailAddress").focus();
// Opening curly braces should appear on the same line as the declaration they open
// Dollar signs are legal identifiers, but usually denote libraries (like JQuery) and
// can be confusing if you are not using those libraries.
function getElem (id) {
return document.getElementById(id);
}
function validate(evt) {
var inputs = document.querySelectorAll(".validate");
// It's better logic to assume false, which avoids "false positives"
var isValid = false;
// Loop through the fields that need validation
for (var i = 0; i < inputs.length; ++i){
var message = ""; // This is the potential error message
// Validate the input according to its id:
switch (inputs[i].id) {
case "firstName" :
// You can't check a single value against a comma-separated list, you have to check
// it against each value you are interested in:
isValid = (inputs[i].value !== "Cherry" && inputs[i].value !== "Micheal" &&
inputs[i].value !== "Sandra" && inputs[i].value !== "Cookie") ? false : true;
message = (!isValid) ? "This person does not exist." : "";
break;
case "orderNumber" :
// Remember, HTML form fields always return strings, not numbers
isValid = (inputs[i].value !== "3134" && inputs[i].value !== "4234" &&
inputs[i].value !== "9234" && inputs[i].value !== "3566") ? false : true;
message = (!isValid) ? "Invalid Order Number." : "";
break;
case "dateOfOrder" :
isValid = (inputs[i].value !=='12-07-23' && inputs[i].value !== '15-04-24' &&
inputs[i].value !== '16-02-01' && inputs[i].value !== '14-01-12') ? false : true;
message = (!isValid) ? "Date doesn't exist in system" : "";
break;
case "emailAddress" :
isValid = (inputs[i].value != "cherryjackson#gmail.com" &&
inputs[i].value !== "michealroberts#yahoo.com" &&
inputs[i].value !== "sandrabell#hotmail.com" &&
inputs[i].value !== "cookiedanny#outlook.com") ? false : true;
message = (!isValid) ? "The email doesn't exist" : "";
break;
}
// Update the UI with the correct message:
inputs[i].nextElementSibling.textContent = message;
}
if(!isValid) {
// cancel the submission if we're invalid
evt.preventDefault(); // Cancel the form's submission
evt.stopPropagation(); // Don't bubble the event
}
}
});
body{
background-color:#FBFBE8;
}
/* Tells HTML5 to find the font-type-face that my OS has and then use that for heading 1
and also centers the first heading */
h1{
font-family:Arial, Helvetica, sans-serif;
text-align:center;
}
/* Tells HTML5 to use any of the font-types for my first paragraph in HTML source file
if one is not available. Also clears some white space
from the left margin of the paragraph and finally tells it to give that paragraph
a size of 20 pixels. */
p {
font-family:Arial, Helvetica, sans-serif;
padding: 20px;
font-size:20px;
}
label{
float: left;
width: 11em;
text-align: right;
font-family:Arial, Helvetica, sans-serif;
color:#800000;
}
input{
margin-left: 1em;
margin-bottom:.5em;
}
span {
color: red;
}
.field_set_1{
border-color: purple;
border-style: solid;
}
#form_submission{ background-color:black; color:white; }
legend{
font-family:Arial, Helvetica, sans-serif;
color:blue;
}
/* All of the classes are just for positioning and floating the four
same images around the form input information */
.Wrap1{
float:right;
margin:40px;
width:200px;
height:200px;
}
.Wrap2{
float:left;
margin:40px;
width:200px;
height:200px;
}
.clearfix {
clear: both;
}
<form id="cookieForm" name="cookieForm" action="submit form.html" method="get">
<fieldset class="field_set_1">
<!-- Below sets the title of the form-->
<legend>Customer Order Form Information:</legend>
<!-- Creates the first left label to specify what should be placed in the text box
the the right of the label. The rest below does the same.-->
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" class="validate">
<span id="firstname_error">*</span><br>
<label for="orderNumber">Order Number:</label>
<input type="text" id="orderNumber" name="orderNumber" class="validate">
<span id="orderNumber_error">*</span><br>
<label for="dateOfOrder">Date of Order:</label>
<input type="text" id="dateOfOrder" name="dateOfOrder" class="validate">
<span id="dateOfOrder_error">*</span><br>
<label for="emailAddress">Email Address:</label>
<input type="text" id="emailAddress" name="emailAddress" class="validate">
<span id="emailAddress_error">*</span><br>
<label> </label>
<!-- Always use a "submit" button to initiate form submission, even
if there will be form validation -->
<input type="submit" id="form_submission" value="Submit this Form">
</fieldset>
</form>
I've got the input field, need to check the number only, if value of input is number - another div .hidden should display: block; Also I've got multiple eventlistener on four block- onclick this .hidden block is visible, if it possible combine this event with the form input event.
;
(function() {
var amount_list = document.querySelectorAll('.form-row .donate');
var amount_array = [].slice.call(document.querySelectorAll(".form-row .donate"));
var donerForm = document.getElementById('hidden');
var inputDonateField = document.getElementById('donate-price').value;
var inputNumber = /^[0-9]+$/;
var onClickFormVisible = function() {
donerForm.style.display = "block";
};
var amoutn_array = amount_array.map(function(e) {
return e.addEventListener('click', onClickFormVisible);
});
// var onclickInputNumberDonate = function() {
// // If x is Not a Number or
// if (isNaN(inputDonateField) && inputDonateField.length > 0) {
// console.log(inputDonateField);
// return onClickFormVisible();
//
// } else {
// return false;
// }
// };
function validateForm() {
if (inputDonateField === null || inputDonateField === "") {
alert("Name must be filled out");
return false;
}
}
})();
#hidden {
display: none;
}
<div class="form-row">
<label>Label</label>
<div class="donate">50kr</div>
<div class="donate">100kr</div>
<div class="donate">200kr</div>
<div class="donate">500kr</div>
</div>
<div class="form-row">
<div class="form-col doner-price">
<label for="donate-price">
only number
<input type="text" id="donate-price" name="name" value="">
</label>
</div>
</div>
<div id="hidden">TExt here</div>
Most browsers support type="number", can also have specified ranges with the min and max attributes, and can use the step attribute to accept only certain numbers (for example whole numbers).
<input type="number" min="0" max="50" step="1" />
On submit of the form, you'll still want to verify of course.
IsNan() is useful for filtering out some inputs. Comparing against a regex like new RegExp('^[0-9]+$'); is a safe bet.
As for:
if it possible combine this event with the form input event.
I don't quite know what you're asking.
If you are asking how to validate on both onclick and onsubmit events, just create a function for the validation, like validateInput() and call it for onclick and onsubmit.
element.onclick = function() {
if (isValidInput(inputValue)) {
// More code here
}
}
form.onsubmit = function() {
if (isValidInput(inputValue)) {
// More code here
}
}
function isValidInput(inputValue) {
// Check that input is valid
// Return true / false
}
It's working for me now with keyup input event.
(function() {
var amount_list = document.querySelectorAll('.form-row .donate'); //node-list
var amount_array = [].slice.call(document.querySelectorAll(".form-row .donate")); //node-list to array
var donerForm = document.getElementById('hidden');
var inputDonateField = document.getElementById('donate-price');
var inputNumber = /^[0-9]+$/;
var onClickFormVisible = function() {
donerForm.style.display = "block";
};
var onInputTypeNumber = function() {
if (inputNumber.test(inputDonateField.value)) {
donerForm.style.display = "block";
} else {
return false;
}
};
//onclick event for each amount images
var amoutn_array = amount_array.map(function(e) {
return e.addEventListener('click', onClickFormVisible);
});
//input event only if value === number
inputDonateField.addEventListener("keyup", onInputTypeNumber);
})();
.form-row{display:flex; margin:2rem;}
.donate{
background: #007DBD;
width: 75px;
height:50px;
padding: 1rem;
border: 1px solid black;
}
#hidden{
display:none;
width: 100px;
height:150px;
background: gray;
color: black;
text-align:center;
padding: 2rem;
}
<div class="form-row">
<label>Label</label>
<div class="donate">50kr</div>
<div class="donate">100kr</div>
<div class="donate">200kr</div>
<div class="donate">500kr</div>
</div>
<div class="form-row">
<div class="form-col doner-price">
<label for="donate-price">
only number
<input type="text" id="donate-price" name="name" value="">
</label>
</div>
</div>
<div id="hidden">Only if Input value === to number.You are see this block;</div>