Disable Submit button until all form fields are validated - javascript

I have a function to validate all fields, but I also want to disable the submit button until the fields are filled out AND validation is complete. What is the best way to go about doing this? I'm very new to JavaScript so very specific instructions/explanation is appreciated :)
function fieldValidation() {
var name = document.forms['RegForm']['Name'].value;
var address = document.forms['RegForm']['Address'].value;
var email = document.forms['RegForm']['EMail'].value;
var password = document.forms['RegForm']['Password'].value;
var telephone = document.forms['RegForm']['Telephone'].value;
var job = document.forms['RegForm']['Job'].value;
var comment = document.forms['RegForm']['Comment'].value;
var fullName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var phnFormat = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/;
if (name === '') {
alert('Please enter your name.');
return false;
}
if (!fullName.test(name)) {
alert('Please make sure we have your full name.');
return false;
}
if (address === '') {
alert('Please enter your address.');
return false;
}
if (email === '') {
alert('Please enter your e-mail address.');
return false;
}
if (password === '') {
alert('Please enter a password.');
return false;
}
if (telephone === '') {
alert('Please enter your telephone number.');
return false;
}
if (!phnFormat.test(telephone)) {
alert('Please enter your phone number in the following format: (123) 555-1212)');
return false;
}
if (job.value === '') {
alert('Please select a job choice.');
return false;
}
if (comment.value === '') {
alert('Please enter a comment.');
return false;
}
return true;
}
<div class="container">
<main>
<form name="RegForm" action="/submit.php" onsubmit="return fieldValidation()" method="post">
<p>Name: <input type="text" size=65 name="Name" id="nameInput"> </p><br>
<p>Address: <input type="text" size=65 name="Address"> </p><br>
<p>E-mail Address: <input type="email" size=65 name="EMail"> </p>
<input type="checkbox" id="confirmApp" name="confirm">
<label for="confirmApp">I want to receive an email confirming my application.</label>
<br>
<p>Password: <input type="password" size=65 name="Password"> </p><br>
<p>Telephone: <input type="tel" size=65 name="Telephone"> </p><br>
<label for="jobChoice">Job Choice:</label>
<select name="Job" id="jobChoice">
<option value="">--- Select Job Choice ---</option>
<option value="IT">IT</option>
<option value="Human Resources">Human Resources</option>
<option value="Maintenance">Maintenance</option>
<option value="Management">Management</option>
<option value="Other">Other</option>
</select></p><br><br>
<p>Comments: <textarea cols="100" rows="10" name="Comment"> </textarea></p>
<p><input type="submit" value="send" name="Submit" id="submitBtn">
<input type="reset" value="Reset" name="Reset"></p>
</form>
</main>
</div>

You could do it in a couple of ways:
You could have a onclick="your validation function" for each input running your validation code.
Or you could add the required tag to each required input, this way the user cant submit the form unless every required field is filled in a.e. <input type="text" size="65" name="Name" id="nameInput"required>, however option two does not hide the submit button.
If you only want to disable the submission and not the submit button persé I'd suggest using the required tag for the relevant input fields.

Related

Form Validation in JQuery Mobile

I'm trying to add validation to the form I made
<fieldset>
<legend>ENTER YOUR INFORMATION HERE FOR DELIVERY</legend>
<form action="" name="deliveryform">
Name* :<input type="text" name="name" id="name">
Phone Number* : <input type="text" name="phonenumber" id="phonenumber">
<span id="warning1"></span>
Address* : <textarea name="address" id="address" required></textarea>
Email* : <input type="text" name="email" id="email">
<span id="warning2"></span>
<input type="submit" id="submitbutton" value="Submit" onsubmit=" return validation()">
</form>
</fieldset>
Javascript
function validation()
{
var name = document.getElementsByName("name").value;
var phonenumber =document.getElementsByName("phonenumber").value;
var email = document.getElementById("email").value;
var emailformat = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$";
if(name == ""|| null)
{
alert("Please Enter Your Name!");
return false;
}
if(isNaN (phonenumber))
{
document.getElementById("warning1").innerHTML ="Enter numbers only";
return false;
}
if(!email.match(emailformat))
{
document.getElementById("warning2").innerHTML="Please enter the correct format. Example : Abc1234#gmail.com"
return false;
}
else
{
alert("Submitted Successfully")
}
}
Nothing changed except ''Error Loading Page '' message appeared.
Did I miss something?
I thought coding in without and with Jquery in HTML is the same thing..

Submit Button Not working but if I remove its JavaScript it works

This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.

Javascript form validation no alert on submit

I am trying to validate my form before submitting it but the form is being submitted anyway without any alerts coming up, even though the form is being submitted blank. When the submit button is clicked I want to make sure information has been completed and is correct, and when it is blank or incorrect an alert should come up without submitting the form.
Thanks
HTML
<!DOCTYPE html>
<html>
<head>
<title>Oaktown Football Club</title>
<meta charset="UTF-8">
<script src="formValidation.js"></script>
</head>
<body>
<header>
<img src="logo.png" alt="Oaktown Football Club Logo"/>
<h1>Oaktown Football Club</h1>
<nav>
Homepage
Competitions
Contact
</nav>
</header>
<section>
<h2>Contact Us</h2>
<article>
<h3>Secretary</h3>
<p>Name: Laci Tanner</p>
<p>Phone: (02) 6620 3324</p>
<p>Email: secretary#oaktownfa.com.au</p>
<h3>Leave us a message</h3>
<form method="post" action="actionPage.html" name="contactForm" onsubmit="return formValidation();">
<label>Full Name:</label><br>
<input type="text" size="35" name="fullName" id="name"><br>
<br><label>Email:</label><br>
<input type="text" size="35" name="email" id="email"><br>
<br><label>Phone:</label><br>
<input type="text" size="35" name="phone" id="phone"><br>
<br><label>Team:</label><br>
<select name="team"><br>
<option>Please Choose</option>
<option>Adults</option>
<option>Under 12s</option>
<option>Under 6s</option>
</select><br>
<br><label>I am:</label><br>
<select name="Member"><br>
<option>Please Choose</option>
<option>Thinking about joining the club</option>
<option>Already a club member</option>
</select><br>
<br><label>Comments:</label><br>
<textarea id="comments" type="text" rows="5" cols="75"></textarea><br>
<br><input id="submit" type="submit" value="Submit"><br>
<br><input type="reset">
</form>
</article>
</section>
<footer>
<p>Copyright - Oaktown Football Club</p>
</footer>
</body>
</html>
JavaScript
function formValidation()
{
var name = document.contactForm.fullName;
var email = document.contactForm.email;
var phone = document.contactForm.phone;
var comment = document.contactForm.comment;
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address!");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (phone.value == "") {
alert("Please enter your phone number!");
phone.focus();
return false;
}
if (phone.length < 2) {
alert("Please enter a valid phone number!");
phone.focus();
return false;
}
if (comments.value == "") {
alert("Please leave us a comment!");
comments.focus();
return false;
}
{
return true;
}
}
It seems you had stored the value of the 'Full Name' in the variable 'name', but you were checking in your first 'if' block, you were checking if "fullName.value == ''".
Thus, a 'Reference Error' was being thrown.
After correcting it to if "name.value == ''", the code works fine.
Please find below the working code in JSBin :-
http://jsbin.com/kemokijucu/edit?html,js,console,output
You get name :
var name = document.contactForm.fullName;
But check by fullName :
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
Please up the code :)
You have made mistake in fetching & using name element from the form. Below is the correction in JS.
function formValidation() {
var fullName = document.contactForm.name;
var email = document.contactForm.email;
var phone = document.contactForm.phone;
var comment = document.contactForm.comment;
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address!");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (phone.value == "") {
alert("Please enter your phone number!");
phone.focus();
return false;
}
if (phone.length < 2) {
alert("Please enter a valid phone number!");
phone.focus();
return false;
}
if (comments.value == "") {
alert("Please leave us a comment!");
comments.focus();
return false;
} {
return true;
}
}
<title>
Oaktown Football Club</title>
<body>
<header>
<img src="logo.png" alt="Oaktown Football Club Logo" />
<h1>Oaktown Football Club</h1>
<nav>
Homepage
Competitions
Contact
</nav>
</header>
<section>
<h2>Contact Us</h2>
<article>
<h3>Secretary</h3>
<p>Name: Laci Tanner</p>
<p>Phone: (02) 6620 3324</p>
<p>Email: secretary#oaktownfa.com.au</p>
<h3>Leave us a message</h3>
<form method="post" action="actionPage.html" name="contactForm" onsubmit="return formValidation();">
<label>Full Name:</label>
<br>
<input type="text" size="35" name="fullName" id="name">
<br>
<br>
<label>Email:</label>
<br>
<input type="text" size="35" name="email" id="email">
<br>
<br>
<label>Phone:</label>
<br>
<input type="text" size="35" name="phone" id="phone">
<br>
<br>
<label>Team:</label>
<br>
<select name="team">
<br>
<option>Please Choose</option>
<option>Adults</option>
<option>Under 12s</option>
<option>Under 6s</option>
</select>
<br>
<br>
<label>I am:</label>
<br>
<select name="Member">
<br>
<option>Please Choose</option>
<option>Thinking about joining the club</option>
<option>Already a club member</option>
</select>
<br>
<br>
<label>Comments:</label>
<br>
<textarea id="comments" type="text" rows="5" cols="75"></textarea>
<br>
<br>
<input id="submit" type="submit" value="Submit">
<br>
<br>
<input type="reset">
</form>
</article>
</section>
<footer>
<p>Copyright - Oaktown Football Club</p>
</footer>
</body>
Do try and debug the same using console in the browser.
You can change the type attribute of email field to email for auto email validation on the field.

Validating a Form with text boxes and radio buttons using JavaScript

I am trying to make an order form that validates all entries to make sure the text boxes have data, and that the one of the 3 radio buttons is selected. As you can see in my code, I used a function to validate all the text boxes that are required, but I can not get the radio buttons to validate. I have tried if else statements and loops, but none of them have worked for me. I have tried including the radio button validation in the current function, and also tried making a new function just for it. Please help!
HTML here:
<form action="FormProcessor.html.html" method="get" onsubmit="return check();">
<select>
<option>Hand Tool</option>
<option>Saw</option>
<option>Hammer</option>
<option>Screwdriver</option>
<option>Wrench</option>
<option>Pliers</option>
</select>
<select>
<option>Power Tools</option>
<option>Circular Saw</option>
<option>Sabre Saw</option>
<option>Drill</option>
<option>Belt Sander</option>
<option>Table Saw</option>
</select>
<label>
<select>
<option>Materials</option>
<option>Plywood</option>
<option>Shingles</option>
<option>Nails</option>
<option>Screws</option>
</select>
</label>
<label>First Name
<input type="text" id="firstname" name="firstname" placeholder="First Name"></label>
<label>Last Name
<input type="text" id="lastname" name="lastname" placeholder="Last Name"></label> <br><br>
<label>Street Address 1
<input type="text" id="street_address_1" name="street_address_1" placeholder="Address 1"></label> <br><br>
<label>Street Address 2
<input type="text" id="street_address_2" name="street_address_2" placeholder="Address 2"></label> <br><br>
<label>City
<input type="text" id="city" name="city" placeholder="City"></label>
<label>State
<input type="text" id="state" name="State" placeholder="State"></label>
<label>Zip
<input type="text" id="zip_code" name="zip_code" placeholder="Zip"></label> <br><br>
<label>Phone
<input type="text" id="phone" name="phone" placeholder="Phone"></label>
<label>Fax
<input type="text" id="fax" name="fax" placeholder="Fax"></label> <br><br>
<label>Payment Method?
<input type="radio" name="card_type" id="visa">
<label for="visa">Visa</label>
<input type="radio" name="card_type" id="mastercard">
<label for="mastercard">MasterCard</label>
<input type="radio" name="card_type" id="americanexpress">
<label for="americanexpress">American Express</label><br><br>
<label>Credit Card Number
<input type="text" id="credit_card_number" name="credit_card_number" placeholder="Credit Card Number"></label> <br><br>
<label>Experiation Month
<select id = month>
<option>Month</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
</label>
<label>Experiation Year
<select id = year>
<option>Year</option>
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select> <br>
</label> <br><br>
<input type="submit" value="Submit Order">
JS Here
function check() {
var errormessage = "";
if (document.getElementById('firstname').value == "") {
errormessage += 'Please enter a First Name \n';
}
if (document.getElementById('lastname').value == "") {
errormessage += 'Please enter a Last Name \n';
}
if (document.getElementById('street_address_1').value == "") {
errormessage += 'Please enter your Street Address \n';
}
if (document.getElementById('city').value == "") {
errormessage += 'Please enter a City \n';
}
if (document.getElementById('state').value == "") {
errormessage += 'Please enter a State \n';
}
if (document.getElementById('zip_code').value == "") {
errormessage += 'Please enter a Zip Code \n';
}
if (document.getElementById('phone').value == "") {
errormessage +='Please enter a Phone Number \n';
}
if (document.getElementById('credit_card_number').value == "") {
errormessage += 'Please enter a Credit Card \n';
}
if (document.getElementById('month').value == "") {
errormessage += 'Please enter a Month \n';
}
if (document.getElementById('year').value == "") {
errormessage += 'Please enter a Year \n';
}
if (errormessage != "") {
alert(errormessage);
return false;
}
}
How about setting up a function to validate a radio button, something like this:
function validateRadio(radioGroup) {
for (i = 0; i < radioGroup.length; ++ i) {
if (radioGroup[i].checked) return true;
}
return false;
}
And then in your check() function you can call the validateRadio() function and pass it the radio group you want to check:
if(!validateRadio(document.forms["formid"]["card_type"])) {
errormessage +='Please select a Payment Method\n';
}

How would it be possible to call multiple js functions to a single form?

Now when I run this code, the form's function do not run. Why, Im not sure. Is it because of the doall() function I placed in my js. I did it specifically to tell the button tag thats the function to ultimately run. Is placing functions within 1 whole function considered bad? Where did I go wrong with my javascript and html pairings? I am ultimately trying to have one part of the form validate with alerts, have the total spit a given value automatically after a radio is chosen, and as you click the submit button after everything is filled, it creates that var sign.
<form name="form1" action="" onsubmit="return doall{};">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" size="12" placeholder="First Name">
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" size="12" placeholder="Last Name">
<label for="address">Address:</label>
<input type="text" name="address" id="address" size="40" placeholder="Address">
<label for="city">City:</label>
<input type="text" name="city" id="city" size="40" placeholder="City">
<label for="state">State:</label>
<input type="text" name="state" id="state" size="40" placeholder="State">
<label for="country">Country:</label>
<input type="text" name="country" id="country" size="40" placeholder="Country">
<label for="zipcode">Zip Code:</label>
<input type="text" name="zipcode" id="zipcode" placeholder="Zip Code">
<p><label for="email">Email:</label>
<input type="text" name="email" id="email" size="30" placeholder="Email Address"></p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" size="20" placeholder="Password">
<p><label for="repass">Retype Password:</label>
<input type="password" name="repass" id= "repass" size="20" placeholder="Re-type Password"></p>
<p><b>Choose the Program you would like to purhase:</b></p>
<table align ="center">
<tr>
<td><input type="radio" name="offers" value= "Basic" id="chkbox" onchange="ontotal()"></td>
<td>Basic</td>
<td>$<span>19.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Premium" id="chkbox" onchange="ontotal()" ></td>
<td>Premium</td>
<td>$<span >35.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Super" id="chkbox" onchange="ontotal()"></td>
<td>Super</td>
<td>$<span >59.99</span></td>
</tr>
</table>
<p>
Total:
<input type="text" id="prototal" size="8" value="0" >
</p>
</form>
<button type="button" onclick="doall();">Submit</button>
<p id="submit"></p>
` function formval() {
var first = document.getElementById("fname")
var second = document.getElementById("lname")
var third = document.getElementById("address")
var fourth = document.getElementById("city")
var fifth = document.getElementById("state")
var sixth = document.getElementById("country")
var seventh = document.getElementById("zipcode")
var fire = document.getElementById("email")
var sense = document.getElementById("password")
var retype = document.getElementById("repass")
if (first == ""){
alert("Please enter first name");
return false;
}
if (second == ""){
alert("Please enter last name");
return false;
}
if (third == ""){
alert("Please enter address");
return false;
}
if(fourth == ""){
alert("Please enter city");
return false;
}
if (fifth == ""){
alert("Please enter state");
return false;
}
if (sixth == ""){
alert("Please enter county");
return false;
}
if (seventh == ""){
alert("Please enter zip code");
return false;
}
if (fire == ""){
alert("Please enter email address");
return false;
}
if (sense == ""){
alert("Please enter a password");
return false;
}
if (retype == ""){
alert("Please enter your typed password");
return false;
}
var sign = "Thank you for submission. Your purchase order instructions will be emailed shortly!";
document.getElementById("sub").innerHTML = sign;
}
var programprices = new Array();
programprices["Basic"]=19.99;
programprices["Premium"]=35.99;
programprices["Super"]=59.99;
function ontotal(){
var producttotal=0;
var calform = document.forms["form1"]
var offers = calform.elements["offers"]
for(var i = 0; i < offers.length; i++)
{
if (offers[i].checked)
{
producttotal = programprices[offers[i].value];
break;
}
}
return producttotal;
}
function caltotal(){
var price = ontotal;
var presentme = document.getElementById('prototal')
presentme.innerHTML = price
}
function doall(){
formval();
ontotal();
caltotal();
}
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal); `
https://jsfiddle.net/Lnehnkaz/
First correct the above mentioned errors.
There is nothing wrong with calling some functions from another function. If you want multiple submit handlers, put the submit button within the form, change it to type="submit" and use the addEventListener method.
This works, when you give the form the attribute id="form1":
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal);

Categories