Changing HTML label color with javascript - javascript

I have a form that I need to check for no entries and things like that. Right now the form will change the color of the form fields to red but I need it to change the labels to red also. Since labels are not form elements my current method is making it a tad difficult to change the labels as well. Any suggestions I can implement?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form Test</title>
<script type="text/javascript">
function validate(){
var errors = new Array();
for( var x = 0; x < document.forms[0].elements.length; x++ ){
if( document.forms[0].elements[x].type == "text" ){
if( document.forms[0].elements[x].value == "" ){
errors.push("The " + document.forms[0].elements[x].name + " field cannot be blank.\n");
document.forms[0].elements[x].className = "in_error";
}
}
if( document.forms[0].elements[x].type == "select-one" ){
if( document.forms[0].elements[x].selectedIndex == 0 ){
errors.push( "The " + document.forms[0].elements[x].name + " field cannot be blank.\n" );
document.forms[0].elements[x].className = "in_error";
}
}
if( document.forms[0].elements[x].type == "password" ){
if( document.forms[0].elements[x].value == ""){
errors.push( "The " + document.forms[0].elements[x].name + " field cannot be blank.\n" );
document.forms[0].elements[x].className = "in_error";
}
}
}
if( errors.length == 0 ){
return true;
}else{
clear_errors( errors );
show_errors( errors );
return false;
}
}
function clear_errors( errors ){
var div = document.getElementById( "errors" );
while( div.hasChildNodes() ){
div.removeChild(div.firstChild);
}
}
function show_errors( errors ){
var div = document.getElementById( "errors" );
for(var x = 0; x < errors.length; x++){
var error = document.createTextNode( errors[x] );
var p = document.createElement( "p" );
p.appendChild( error );
div.appendChild( p )
}
}
window.onload = function( ){
document.forms[0].onsubmit = validate;
}
</script>
<style type="text/css">
#errors{
color: #F00;
}
.in_error{
background-color: #F00;
}
</style>
</head>
<body>
<div id="errors"></div>
<form action="http://ingenio.us.com/examples/echo" method="post">
<div class="mainContainer" style="width:650px; margin: 0 auto; text-align:center;">
<div class="contactInfo" style="text-align:center; width:650px;">
<fieldset>
<legend style="text-align:left;">Contact Info</legend>
<label id="firstNameLabel" for="firstName">First Name: </label><input name="First Name" id="firstName" type="text" size="15" maxlength="15" />
<label id="lastNameLabel" for="lastName">Last Name: </label><input name="Last Name" id="lastName" type="text" size="15" maxlength="15" />
<label id="middleInitialLabel" for="middleInitial">Middle Initial: </label><input name="Middle Initial" id="middleInitial" type="text" size="4" maxlength="1" /><br /><br/>
<label id="streetAddressLabel" for="streetAddress">Street Address: </label><input name="Street Address" id="streetAddress" type="text" size="58" maxlength="55" /> <br /><br />
<label id="cityLabel" for="city">City: </label><input name="City" id="city" type="text" size="30" maxlength="28" />
<label id="stateLabel" for="state">State: </label>
<select name="State" id="state">
<option></option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<label name="zipLabel" for="zip">Zip: </label><input name="Zip" id="zip" type="text" size="7" maxlength="5" /><br /><br />
</fieldset>
</div><br /><br />
</div>
<div class="mainContainerTwo" style="width:450px; margin: 0 auto; text-align:center;">
<div class="userInfo" style="text-align:center; width:450px;">
<fieldset>
<legend style="text-align:left;">User Info</legend>
<label name="usernameLabel" for="username">Username: </label><input name="Username" id="username" type="text" size="20" maxlength="15" /><br /><br />
<label name="passwordLabel" for="password">Password: </label><input name="Password" id="password" type="password" size="20" maxlength="15" /><br /><br />
<label name="passwordConfirmLabel" for="passwordConfirm">Confirm Password: </label><input name="Confirm Password" id="passwordConfirm" type="password" size="20" maxlength="15" /><br /><br />
<input type="submit" value="Submit" />
</fieldset>
</div>
</div>
</form>
</body>
</html>

A quick fix would be traversing from the input element to the previous sibling, which in this case is the label element. After that you can add class in_error to your label element.
Add the following code line inside the three if-blocks
document.forms[0].elements[x].previousSibling.className = "in_error";
Then you should also change your CSS to the following, in order to set the red background color to the inputs and red foreground color to the labels.
input.in_error{
background-color: #F00;
}
label.in_error {
color: #F00;
}
Is there any reason why you are not using jQuery? If not, I strongly suggest you to take it into use. It makes DOM manipulation like this super easy.

Related

My javaScript just stopped working?

So I'm trying to create checks so that if someone hasn't entered a zip code, phone number, or email address properly then the javascript will display an alert and the form won't be submitted. If any of the fields aren't filled (null || =="") then the javascript will also display an alert and wont submit the form.
It was working just fine but then all of the sudden stopped working... I've been looking at it for awhile now and cannot figure out why.
Here's my code (.php):
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Adding Companies</title>
<link rel="stylesheet" type="text/css" href="../ResponsiveTopNavDropdown.css" />
<meta name="viewport" content="width=device-width">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="toggleNav.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<div class="header"></div>
<div id="toggleNav">Show/Hide Navigation</div>
<nav id="nav">
<?php include('../nav.html'); ?>
</nav>
<h1 id="mainheader">WELCOME TO MISSISSIPPI VALLEY CHAPTER 123</h1>
<section class="content-wide">
<?php
session_start();
if ($_SESSION['check'] != "true") {
header('Location: http://www.mississippivalleyashrae.org/Admin/admin_login.php');
}
$_SESSION['my_company'] = null;
?>
<h3><strong>You're currently in the process of: Adding a Company<strong></h3>
<table width = "760" border = "0" align = "center" cellpadding="0" cellspacing="1" bgcolor = "#cccccc">
<tr>
<form onSubmit="return validateCompany()" action="adding_manufacturer.php" method="post">
<td>
<table width="100%" border="0" cellpadding="5" cellspacing="0" bgcolor="#EEEEEE">
<tr>
<td colspan="3"><strong> Enter the Information for this New Company </strong></td>
</tr>
<tr>
<td colspan="3" align = "left">
Company Name<br />
<input type="text" name="company_name" id="company_name" placeholder="My Company .Inc"
size="100" maxlength="125"></td>
</tr>
<tr>
<td colspan="3" align = "left">
Address<br />
<input type="text" name="address" id="address" placeholder="1234 My Street Ave."
size="100" maxlength="100"></td>
</tr>
<tr>
<td align = "left" width="250">
City<br />
<input type="text" name="city" id="city" placeholder="Rock Island" size="30" maxlength="30"></td>
<td align = "left" width="250">
State<br />
<select name="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select></td>
<td align = "left" width="250">
Zip-Code<br />
<input type="text" name="zip" id="zip" placeholder="61201" size="6" maxlength="6"></td>
</tr>
<tr>
<td align = "left" width="250">
Phone<br />
<input type="text" name="phone" id="phone" placeholder="515-555-0000" size="12" maxlength="12"></td>
<td colspan="2" align = "left" width="250">
Email Address<br />
<input type="text" name="email" id="email" placeholder="myemail24#gmail.com"
size="50" maxlength="50"></td>
</tr>
<tr>
<td colspan="3">
<br />
<input type ="submit" name="submit" id="mySubmit" value="Add This Company"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<p>
**Make sure all information is entered correctly!<br />
If you enter any information incorrectly you can go back and edit it from the
Admin Main page!
</p>
<script src="formValidators.js" type="text/javascript"></script>
</section>
And here's my javascript (formValidators.js):
function validateCompany() {
var checkCompanyName = document.getElementById("company_name").value;
var checkAddress = document.getElementById("address").value;
var checkCity = document.getElementById("city").value;
var checkState = document.getElementById("state").value;
var checkZip = document.getElementById("zip").value;
var checkPhone = document.getElementById("phone").value;
var checkEmail = document.getElementById("email").value;
// checks for any null fields
if ((checkCompanyName==null || checkCompanyName=="") || (checkAddress==null || checkAddress=="") ||
(checkCity==null || checkCity=="") || (checkState==null || checkState=="") ||
(checkZip==null || checkZip=="")|| (checkPhone==null || checkPhone=="") ||
(checkEmail==null || checkEmail=="")){
alert("Please Fill All Fields");
return false;
}
var zipPattern = /^\\d{5}(-\\d{4})?$/;
if (zipPattern.test(checkZip) == false){
alert("Invalid Zip-Code, Please Re-Enter the zip-code in the correct format");
return false;
}
var phonePattern = /^()?\d{3}()?(-|\s)?\d{3}(-|\s)\d{4}$/;
if (phonePattern.test(checkPhone) == false){
alert("Invalid Phone Number, Please Re-Enter the phone number in the correct format");
return false;
}
var emailPattern = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (emailPattern.test(checkEmail) == false){
alert("Invalid Email, Please Re-Enter the email in the correct format");
return false;
}
}
It looks like the problem is in your state drop down:
<select name="state">
There is no ID to get, so your JS is failing, silently I might add.
<select name="state" id="state">
I modified the selector to include an ID and it's now firing properly.

Submit button clears form instead of opening div

I'm trying to open another div that displays what the user entered in the form onsubmit, but the submit button just clears the form, and I can't figure out why. We have to use Javascript to display the results. Here's the code:
<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
h1 {
text-align: center;
color: blue;
font-family: 'Courier';
margin: 30px;
}
h2 {
margin-top: 40px;
margin-left: 500px;
margin-bottom: 20px;
}
#divresults {
display: none;
}
</style>
</head>
<body>
<div id="customerform">
<form onsubmit="return showResults();">
<p>First Name: <input type="text" id="fname" value="" required /></p>
<p>Last Name: <input type="text" id="lname" value="" required /></p>
<p>Street Address: <input type="text" id="address" value="" required /></p>
<p>City: <input type="text" id="city" value="" required /></p>
<p>State:
<select id="states" required>
<option id="statedefault" value="">Please select your state</option>
<option value="Alabama">Alabama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="Arkansas">Arkansas</option>
<option value="California">California</option>
<option value="Colorado">Colorado</option>
<option value="Connecticut">Connecticut</option>
<option value="Delaware">Delaware</option>
<option value="Florida">Florida</option>
<option value="Georgia">Georgia</option>
<option value="Hawaii">Hawaii</option>
<option value="Idaho">Idaho</option>
<option value="Illinois">Illinois</option>
<option value="Indiana">Indiana</option>
<option value="Iowa">Iowa</option>
<option value="Kansas">Kansas</option>
<option value="Kentucky">Kentucky</option>
<option value="Louisiana">Louisiana</option>
<option value="Maine">Maine</option>
<option value="Maryland">Maryland</option>
<option value="Massachusetts">Massachusetts</option>
<option value="Michigan">Michigan</option>
<option value="Minnesota">Minnesota</option>
<option value="Mississippi">Mississippi</option>
<option value="Missouri">Missouri</option>
<option value="Montana">Montana</option>
<option value="Nebraska">Nebraska</option>
<option value="Nevada">Nevada</option>
<option value="New Hampshire">New Hampshire</option>
<option value="New Jersey">New Jersey</option>
<option value="New Mexico">New Mexico</option>
<option value="New York">New York</option>
<option value="North Carolina">North Carolina</option>
<option value="North Dakota">North Dakota</option>
<option value="Ohio">Ohio</option>
<option value="Oklahoma">Oklahoma</option>
<option value="Oregon">Oregon</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Rhode Island">Rhode Island</option>
<option value="South Carolina">South Carolina</option>
<option value="South Dakota">South Dakota</option>
<option value="Tennessee">Tennessee</option>
<option value="Texas">Texas</option>
<option value="Utah">Utah</option>
<option value="Vermont">Vermont</option>
<option value="Virginia">Virginia</option>
<option value="Washington">Washington</option>
<option value="West Virginia">West Virginia</option>
<option value="Wisconsin">Wisconsin</option>
<option value="Wyoming">Wyoming</option>
</select>
</p>
<p>Zip Code: <input type="text" id="zip" required /></p>
<p>Gender:
<input type="radio" name="sex" value="male" checked />Male
<input type="radio" name="sex" value="female" />Female
</p>
<input type="submit" id="submitbutton" />
<input type="reset" id="clear" value="Clear" />
</form>
</div>
<br/>
<div id="divresults">
<h2>You entered: </h2>
<p>First Name: <span id="first" class="results"></span></p>
<p>Last Name: <span id="last" class="results"></span></p>
<p>Street Address: <span id="street" class="results"></span></p>
<p>City: <span id="cityresult" class="results"></span></p>
<p>State: <span id="stateresult" class="results"></span></p>
<p>Zip: <span id="zipcode" class="results"></span></p>
<p>Gender: <span id="gen" class="results"></span></p>
<input type="button" id="formreset" value="Go Back to Form" onclick="resetForm();" />
</div>
<script>
function showResults() {
//store form values
var fst = document.getElementById("fname").value;
var lst = document.getElementById("lname").value;
var st = document.getElementById("address").value;
var cty = document.getElementById("city").value;
var ste = document.getElementById("states").value;
var zp = document.getElementById("zip").value;
var gndr = "male";
var genders = document.getElementsByName("sex");
for (var i = 0; i < 2; i++) {
if (genders[i].checked) {
gndr = radios[i].value;
break;
}
}
clearForm();
//switch divs
document.getElementById("customerform").style.display = "none";
document.getElementById("divresults").style.display = "block";
//display results
document.getElementById("first").innerHTML = fst;
document.getElementById("last").innerHTML = lst;
document.getElementById("street").innerHTML = st;
document.getElementById("cityresult").innerHTML = cty;
document.getElementById("stateresult").innerHTML = ste;
document.getElementById("zipcode").innerHTML = zp;
document.getElementById("gen").innerHTML = gndr;
return false;
}
function clearForm() {
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("address").value = "";
document.getElementById("city").value = "";
document.getElementById("states").value = "";
document.getElementById("zip").value = "";
}
function resetForm() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("street").innerHTML = "";
document.getElementById("cityresult").innerHTML = "";
document.getElementById("stateresult").innerHTML = "";
document.getElementById("zipcode").innerHTML = "";
document.getElementById("gen").innerHTML = "";
document.getElementById("customerform").style.display = "block";
document.getElementById("divresults").style.display = "none";
}
</script>
</body>
</html>
You have an error Uncaught ReferenceError: radios is not defined, in the for loop you are using radios[i].value which should be genders[i].value
for (var i = 0; i < 2; i++) {
if (genders[i].checked) {
gndr = genders[i].value;
break;
}
}
Demo: Fiddle

Getting cannot call method of undefined using JQuery Form Validator

I'm using the Jquery form validator (http://formvalidator.net/) and I'm having trouble validating SELECT boxes. I've searched the above site and found NOTHING. I have found this article on StackOverflow. (jQuery select box validation)
But it doesn't work.... I get "cannot call method of undefined".
$(document).ready(function() {
//First validate the form
$.validate({
addValidClassOnAll: true,
rules: {
states: {
requiredState: true
},
color: {
requiredColor: true
},
size: {
requiredSize: true
}
},
onError: function() {
console.log('Form Validation failed');
return false;
},
onSuccess: function() {
console.log('Form is valid!');
return true; //Return False Will stop the submission of the form
}
});
$.validator.addMethod('requiredState', function(value) {
return (value !== 'XX');
}, "State required");
$.validator.addMethod('requiredColor', function(value) {
return (value !== 'select');
}, "Please select a Color");
$.validator.addMethod('requiredSize', function(value) {
return (value !== 'select');
}, "Please select a Size");
});
Using the js file: jquery.form-validator.js, there's no need to preface the $.validate... with the form name. But if I do, the validator doesn't work.
But if I don't, the addMethod() doesn't work... So I'm stuck between a rock and a hard place.
Any suggestions would be helpful.
Thank you, all.
Peter
UPDATE: Here's the watered down HTML
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width" />
<meta name="keywords" content="jquery, plugin, scratchpad, scratchcard, scratch" />
<meta name="description" content="A jQuery plugin to mimic a scratch card or pad behaviour. Allowing you to scratch off an overlay as either a color or image." />
<title>MyTitle for Testing</title>
<!-- CSS -->
<link rel="Stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
<link rel="Stylesheet" type="text/css" href="css/bootstrap-form.css" />
</head>
<body>
<div id="content3">
<div id="content-new" class="contentShipping">
<form id="formNewShip" class="bootstrap-frm" action="someFormProcessor.php" method="post">
<h1 style="float: left;">Enter your shipping address</h1>
<div style="float: left; width: 255px;">
<label style="vertical-align: middle;display:none;">First Name: </label>
<input type="text" id="fname" name="fname" size="25" maxlength="20"
placeholder="First Name" data-validation="alphanumeric" />
<br>
</div>
<div style="float: right; width: 255px;">
<label style="vertical-align: middle;display:none;">Last Name: </label>
<input type="text" id="lname" name="lname" size="35" maxlength="35"
placeholder="Last Name" data-validation="alphanumeric" />
<br>
</div>
<br>
<div style="float: left; width: 262px;">
<label style="vertical-align: middle;display:none;">Address: </label>
<input type="text" id="address" name="address" size="30" maxlength="45"
placeholder="Address" data-validation="alphanumeric" />
<br>
</div>
<div style="float: left; width: 255px;">
<label style="vertical-align: middle;display:none;">Apt/Ste: </label>
<input type="text" id="aptste" name="aptste" size="15" maxlength="10"
placeholder="Apt/Ste" />
<br>
</div>
<div style="float: left; width: 262px;">
<label style="vertical-align: middle;display:none;">City: </label>
<input type="text" id="city" name="city" size="30" maxlength="45"
placeholder="City" data-validation="alphanumeric" />
<br>
</div>
<div style="float: right; width: 255px;">
<label style="vertical-align: middle;display:none;">State: </label>
<select id="states" name="states" title='Select your state.'>
<option value="XX" selected="selected">State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<br>
</div>
<div style="float: left; width: 262px;">
<label style="vertical-align: middle;display:none;">Zip Code: </label>
<input type="text" id="zipcode" name="zipcode" size="30"
maxlength="5" placeholder="Zip Code"
data-validation="USAZipCode" />
<br>
</div>
<div style="float: right; width: 255px;">
<label style="vertical-align: middle;display:none;">Size: </label>
<select id="size" name="size" title='Select your size.'>
<option value="select" selected="selected">Size</option>
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select>
</div>
<div style="float: left; width: 262px;">
<label style="vertical-align: middle;display:none;">Color: </label>
<select id="color" name="color" title='Select your color.'>
<option value="select" selected="selected">Color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
<div style="float: right; width: 255px;">
<label style="vertical-align: middle;display:none;">Email: </label>
<input type="text" id="email" name="email" size="30" maxlength="100"
placeholder="Email" data-validation="email" />
<br>
</div>
<div id="buttons" style="width: 210px;">
<div><button id="btnSubmit" type="submit" class="btn btn-primary center-block">Submit</button></div>
<!-- <div style="float: right;"><button id="btnReset" type="reset" class="btn btn-primary">Reset</button></div>-->
</div>
</form>
</div>
</div>
<div id="templates"></div>
<script type="text/javascript" src="assets/jquery.1.9.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap/bootstrap.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" src="js/jquery_form_validator/jquery.form-validator.js"></script>
</body>
</html>
checkout this Fiddle it works, you have to declare your validation methods before rules declaration and use
$("#formNewShip").validate({})
Edit:
To require firstame, you should add this to your rules:
fname: {
required: true
},
I made a fiddle and it works fine:
http://jsfiddle.net/BzRth/
I added the form selector and removed the onSuccess and onError handlers as they seemed superfluous, but the behaviour is exactly as I would expect.
Check that you're using the same version of the jquery validator code as my fiddle (CDN at http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js)

How to partially validate form fields prior to stripe card validation that's in the same form

I have a form the contains customer shipping information and card details. I'm using http://bassistance.de/jquery-plugins/jquery-plugin-validation/ for validation. Right now, all the form fields are validated on form submit, including stripe card validation. The problem is, if a customer enters his/her card information correctly and other areas of the form are not validated, the charge will still go through. Can I validate the billing information prior to running the stripe validation with one submit button without having to break this up into a two step process? See code below. Thanks!
<div class="stripe-errors"><span class="payment-errors"></span></div>
<form action="charge.php" method="POST" id="payment-form" class="form" >
<div class="pleft">
<label for="firstname">First Name</label>
<input type="text" size="20" value="<?php echo $_SESSION['sfirst'] ?>" name="fname" class="required" placeholder="First"/>
</label>
<label for="lastname">Last Name</label>
<input type="text" size="20" value="<?php echo $_SESSION['slast'] ?>" name="lname" class="required" placeholder="Last"/>
<label for="email">Email</label>
<input type="text" size="20" value="<?php echo $_SESSION['semail'] ?>" name="email" class="required email" placeholder="email#address.com"/>
<label>Shipping Address</label>
<input type="text" size="20" value="<?php echo $_SESSION['saddress'] ?>" name="address" class="required" placeholder="Address"/>
</div>
<div class="pmiddle">
<label>City</label>
<input type="text" size="20" value="<?php echo $_SESSION['scity'] ?>" name="city" class="required" placeholder="City"/>
<label>State</label>
<select id="state" value="<?php echo $_SESSION['sstate'] ?>" name="state" class="required" >
<option value="">Select State</option>
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DC">District of Columbia</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="IA">Iowa</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MA">Massachusetts</option>
<option value="MD">Maryland</option>
<option value="ME">Maine</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MO">Missouri</option>
<option value="MS">Mississippi</option>
<option value="MT">Montana</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="NE">Nebraska</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NV">Nevada</option>
<option value="NY">New York</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="PR">Puerto Rico</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VA">Virginia</option>
<option value="VT">Vermont</option>
<option value="WA">Washington</option>
<option value="WI">Wisconsin</option>
<option value="WV">West Virginia</option>
<option value="WY">Wyoming</option>
</select>
<label>Zip Code</label>
<input type="text" size="20" name="zip" value="<?php echo $_SESSION['szip'] ?>" class="required" minlength="5" placeholder="Zip Code"/>
<label>Product Quantity</label>
<select id="orderquantity" name="orderquantity" >
<option value="1">1 Bottle (30 Day Supply)</option>
<option value="2">2 Bottles (60 Day Supply)</option>
<option value="3">3 Bottles (90 Day Supply)</option>
<option value="4">4 Bottles (120 Day Supply)</option>
<option value="5">5 Bottles (150 Day Supply)</option>
<option value="6">6 Bottles (180 Day Supply)</option>
<option value="7">7 Bottles (210 Day Supply)</option>
<option value="8">8 Bottles (240 Day Supply)</option>
</select>
</div>
<div class="pright">
<label>Card Number</label>
<input type="text" size="20" autocomplete="off" class="card-number" />
<label>CVC Security Code </label>
<input type="text" size="4" autocomplete="off" class="card-cvc"/><a class="small-link" data-toggle="modal" href="#cvcs"/>What's this?</a>
<label>Card Expiration (ex. 01/2015)</label>
<select class="card-expiry-month required ">
<option value="">Month</option>
<option value="01">01 January</option>
<option value="02">02 February</option>
<option value="03">03 March</option>
<option value="04">04 April</option>
<option value="05">05 May</option>
<option value="06">06 June</option>
<option value="07">07 July</option>
<option value="08">08 August</option>
<option value="09">09 September</option>
<option value="10">10 October</option>
<option value="11">11 November</option>
<option value="12">12 December</option>
</select>
<select class="card-expiry-year required">
<option value="">Year</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
</select>
</div>
<div class="checkbox">
<input type="checkbox" style="visibility:hidden;" value="checked" checked="yes" name="agree" class="required">
</div>
<div class="purchasebutton">
<button type="submit" class="submit-button button green" onclick="return loadSubmit();">Purchase</button>
</div>
<div class="cards">
<img src="/images/trial/cards.png">
</div>
</form>
</div>
Form js validation here:
<script src="/js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript" src="https://js.stripe.com/v1/"></script>
<script type="text/javascript" src="/js/modal.js"></script>
<script type="text/javascript">
//this validates customer information form fields
$(document).ready(function() {
$("#payment-form").validate();
});
</script>
<script type="text/javascript">
// this identifies your website in the createToken call below
Stripe.setPublishableKey('<?PHP echo $publishable_api_key ?>');
function stripeResponseHandler(status, response) {
if (response.error) {
// re-enable the submit button
$('.submit-button').removeAttr("disabled");
// show the errors on the form
$(".payment-errors").html(response.error.message);
document.getElementById("processing").style.visibility = "hidden";
} else {
var form$ = $("#payment-form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
$(document).ready(function() {
$("#payment-form").submit(function(event) {
if (!$("input[name=agree]").is(":checked")) {document.getElementById("processing").style.visibility = "hidden";
return false;
} else {
$('.submit-button').attr("disabled", "disabled");
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
return false;
}
});
if (window.location.protocol === 'file:') {
alert("stripe.js does not work when included in pages served over file:// URLs. Try serving this page over a webserver. Contact support#stripe.com if you need assistance.");
}
});
</script>
how about this :
$("#payment-form").submit(function(event) {
$("#payment-form").validate();
if(!$("#payment-form").valid()){
event.preventDefault();
$('.submit-button').removeAttr("disabled");
document.getElementById("processing").style.visibility = "hidden";
return false;
}
if (!$("input[name=agree]").is(":checked") ) {document.getElementById("processing").style.visibility = "hidden";
return false;
}...

Javascript is not working - help

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Form Validation and Dynamic Forms</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById('shipping1').onclick = calcShipping;
document.getElementById('shipping2').onclick = calcShipping;
document.getElementById('shipping3').onclick = calcShipping;
document.getElementById('Text1').onblur = recalculate;
document.getElementById('Text2').onblur = recalculate;
document.getElementById('Text3').onblur = recalculate;
}
function calcShipping() {
document.getElementById('shippingTbx').value = parseFloat(this.value).toFixed(2);
recalculate();
}
function recalculate() {
var prod1, prod2, prod3;
var prod1$ = 1.5;
var prod2$ = 2.25;
var prod3$ = 3.45;
var merchandise$ = 0;
prod1 = parseInt(document.getElementById('Text1').value);
prod2 = parseInt(document.getElementById('Text2').value);
prod3 = parseInt(document.getElementById('Text3').value);
if (!isNaN(prod1)) {
merchandise$ += (prod1 * prod1$)
}
if (!isNaN(prod2)) {
merchandise$ += (prod2 * prod2$)
}
if (!isNaN(prod3)) {
merchandise$ += (prod3 * prod3$)
}
document.getElementById('merchTbx').value = parseFloat(merchandise$).toFixed(2);
var shipping$ = parseFloat(document.getElementById('shippingTbx').value);
var total$ = merchandise$;
if (!isNaN(shipping$))
total$ += shipping$;
document.getElementById('totalTbx').value = parseFloat(total$).toFixed(2);
}
</script>
<style type="text/css">
body{
background:
#F4F0F4
url(topleft.jpg)
no-repeat
top left;
padding-right: 20px;
padding-bottom: 50px;
font: 0:8em Verdana, sans-serif;}
.row{width:98%; overflow:auto;}
div.header {width:20%; text-align:left;}
div.field { width:75%; text-align:left;}
.style1 {width: 367px}
#Text1
{
width: 58px;
}
#Text2
{
width: 58px;
}
#Text3
{
width: 58px;
}
</style>
</head>
<body >
<h2 style = "text-align:center;">Form Validation and Dynamic Forms</h2>
<table border="10" width="600" align="center" bgcolor="#DEB887">
<tr>
<td class="style1">
<form action= "thankupage.html">
<fieldset>
<legend>Product Information:</legend>
<input type="checkbox" name="Product1" id="Checkbox1" value="yes" tabindex="1" /> Product 1 # 1.50/unit
<input id="Text1" type="text" /><br />
<input type="checkbox" name="Product2" id="Checkbox2" value="yes" tabindex="2" /> Product 2 # 2.25/unit
<input id="Text2" type="text" /><br />
<input type="checkbox" name="Product3" id="Checkbox3" value="yes" tabindex="3" /> Product 3 # 3.45.unit
<input id="Text3" type="text" /><br />
</fieldset>
<br />
<div align="left" style="width: 569px">
<fieldset id="Fieldset2" style="position: relative">
<legend> Billing Address </legend>
<div class="row">
<div class="header">Last Name:</div>
<div class="field"><input type="text" name="lname" tabindex="1" /></div>
</div>
<div class="row">
<div class="header">First Name:</div>
<div class="field"><input type="text" name="lname" tabindex="1" /></div>
</div>
<div class="row">
<div class="header">Address:</div>
<div class="field"><input type="text" name="address" tabindex="3" /></div>
</div>
<div class="row">
<div class="header">City:</div>
<div class="field"><input type="text" name="address" tabindex="3" /></div>
</div>
<div class="row">
<div class="header">State:</div>
<select name="State" id="Select1">
<option value="-1"></option>
<option value="73|0">Alabama</option>
<option value="16|1">Alaska</option>
<option value="70|0">Arizona</option>
<option value="75|0">Arkansas</option>
<option value="71|0">California</option>
<option value="72|0">Colorado</option>
<option value="67|0">Connecticut</option>
<option value="69|0">Delaware</option>
<option value="68|0">District of Columbia</option>
<option value="65|0">Florida</option>
<option value="66|0">Georgia</option>
<option value="62|1">Hawaii</option>
<option value="63|0">Idaho</option>
<option value="58|0">Illinois</option>
<option value="59|0">Indiana</option>
<option value="60|0">Iowa</option>
<option value="55|0">Kansas</option>
<option value="56|0">Kentucky</option>
<option value="57|0">Louisiana</option>
<option value="52|0">Maine</option>
<option value="50|0">Maryland</option>
<option value="51|0">Massachusetts</option>
<option value="47|0">Michigan</option>
<option value="48|0">Minnesota</option>
<option value="49|0">Mississippi</option>
<option value="44|0">Missouri</option>
<option value="45|0">Montana</option>
<option value="46|0">Nebraska</option>
<option value="41|0">Nevada</option>
<option value="42|0">New Hampshire</option>
<option value="43|0">New Jersey</option>
<option value="38|0">New Mexico</option>
<option value="39|0">New York</option>
<option value="40|0">North Carolina</option>
<option value="35|0">North Dakota</option>
<option value="36|0">Ohio</option>
<option value="37|0">Oklahoma</option>
<option value="32|0">Oregon</option>
<option value="34|0">Pennsylvania</option>
<option value="30|0">Rhode Island</option>
<option value="31|0">South Carolina</option>
<option value="26|0">South Dakota</option>
<option value="27|0">Tennessee</option>
<option value="28|0">Texas</option>
<option value="23|0">Utah</option>
<option value="24|0">Vermont</option>
<option value="25|0">Virginia</option>
<option value="21|0">Washington</option>
<option value="22|0">West Virginia</option>
<option value="17|0">Wisconsin</option>
<option value="18|0">Wyoming</option>
<option value="-1">------------------------------------</option>
<option value="19|2">Armed Forces Americas</option>
<option value="14|2">Armed Forces Europe</option>
<option value="15|2">Armed Forces Pacific</option>
<option value="-1">------------------------------------</option>
<option value="74|4">American Samoa</option>
<option value="61|4">Guam</option>
<option value="53|4">Marianas Islands</option>
<option value="54|4">Marshall Islands</option>
<option value="64|4">Micronesia</option>
<option value="33|4">Palau</option>
<option value="29|4">Puerto Rico</option>
<option value="20|4">US Virgin Islands</option>
<option value="-1">------------------------------------</option>
<option value="11|3">Alberta</option>
<option value="12|3">British Columbia</option>
<option value="13|3">Manitoba</option>
<option value="8|3">New Brunswick</option>
<option value="9|3">Newfoundland</option>
<option value="5|3">Northwest Territories</option>
<option value="10|3">Nova Scotia</option>
<option value="6|3">Nunavut</option>
<option value="7|3">Ontario</option>
<option value="2|3">Prince Edward Island</option>
<option value="3|3">Quebec</option>
<option value="4|3">Saskatchewan</option>
<option value="1|3">Yukon</option>
</select>
</div>
<div class="row">
<div class="header">Zip:</div>
<div class="field"><input type="text" name="address" tabindex="3" /></div>
</div>
<div class="row">
<div class="header">Phone Number:</div>
<div class="field"><input type="text" name="pnumber" /></div>
</div>
<div class="row">
<div class="header">email:</div>
<div class="field"><input type="text" name="address" tabindex="3"
style="width: 297px" /></div>
</div>
</fieldset>
</div>
<br />
<fieldset>
<legend> Billing Method </legend>
<input type="radio" onclick="javascript:setTimeout('__doPostBack(\'ctl00$mainContentPlaceHolder$shipMethodSelector$shipMethods$3\',\'\')', 0)" value="3.50" name="Saturday"
id="Radio1"/>
<label for="ctl00_mainContentPlaceHolder_shipMethodSelector_shipMethods_3">Saturday Delivery ($3.50)</label> <br />
<input type="radio" onclick="javascript:setTimeout('__doPostBack(\'ctl00$mainContentPlaceHolder$shipMethodSelector$shipMethods$3\',\'\')', 0)" value="5.00" name="Days"
id="Radio2"/>
<label for="ctl00_mainContentPlaceHolder_shipMethodSelector_shipMethods_3">2-3 days Delivery ($5.00)</label> <br />
<input type="radio" onclick="javascript:setTimeout('__doPostBack(\'ctl00$mainContentPlaceHolder$shipMethodSelector$shipMethods$3\',\'\')', 0)" value="7.50" name="Overnight"
id="Radio3"/>
Overnight<label for="ctl00_mainContentPlaceHolder_shipMethodSelector_shipMethods_3"> Delivery ($7.50)</label>
</fieldset>
<br />
<fieldset>
<legend>Order Summary</legend>
<b> Merchandise: </b>:
<input id="Text4" type="text" /><br />
Shipping charges:
<input id="Text5" type="text" /><br />
Sales Tax:
<input id="Text6" type="text" /><br />
<b> Order Total: </b>:
<input id="Text7" type="text" /></fieldset>
<br />
<fieldset>
<legend>Pay with Credit Card</legend>
<b> Card Type: </b>
<select class="coField7 coFieldError" id="ctl00_mainContentPlaceHolder_creditCardPaymentSelector_currentCreditCard_creditCardList1" name="ctl00$mainContentPlaceHolder$creditCardPaymentSelector$currentCreditCard$creditCardList1">
<option value="0">Select Card</option>
<option value="3">Visa</option>
<option value="4">Master Card</option>
<option value="5">Discover</option>
<option value="7">American Express</option>
</select>
<br />
<b> Card Number: </b>: <input type="text" size="10" />
</fieldset>
<input type="submit" value="Submit" />
<br />
</form>
</td>
</tr>
</table>
</body>
</html>
Try moving your method call away from your window.onload.
window.onload = MyFunction;
function MyFunction()
{
document.getElementById('shipping1').onclick = calcShipping;
document.getElementById('shipping2').onclick = calcShipping;
document.getElementById('shipping3').onclick = calcShipping;
document.getElementById('Text1').onblur = recalculate;
document.getElementById('Text2').onblur = recalculate;
document.getElementById('Text3').onblur = recalculate;
}
Short answer: you don't appear to have any element in the document named "shipping1".
Longer answer: The error you're getting is indicating that something on the line
document.getElementById('shipping1').onclick = calcShipping;
is failing. It can't be document since you're not in a using block and it would be very strange if document could be null. The next object being accessed is whatever is returned by getElementById() for the onclick slot. Since there doesn't appear to be any element with that name in the dcument, it's a pretty good guess that that's causing the problem.
Fix your Radio buttons for shipping. You're calling them 'shipping1,2,3' in javascript, but in your html they have the wrong ID's. Also remove their postback event.
<input type="radio" value="3.50" name="Saturday"
id="Shipping1"/>
<label for="Shipping1">Saturday Delivery ($3.50)</label> <br />
<input type="radio" value="5.00" name="Days"
id="Shipping2"/>
<label for="Shipping2">2-3 days Delivery ($5.00)</label> <br />
<input type="radio" value="7.50" name="Overnight"
id="Shipping3"/>
Overnight<label for="Shipping3"> Delivery ($7.50)</label>
Cheers,
~ck
document.getElementById('shipping1')
Above code is "null", means there is no control with the name "shipping1".
document.getElementById('Text1').onblur
This also throws "null" exception as there is no control with the name "shippingTbx" in the html you gave.
function calcShipping() {
// Below code is null
document.getElementById('shippingTbx').value = parseFloat(this.value).toFixed(2);
recalculate();
}
Please make sure you've all the controls and get the element only for the controls available in the html.

Categories