This code was working earlier today, then randomly stopped, something must of changed, but I can't work out what - please see below:
**UPDATE - code update below. Now it correctly recognises if a radio button is checked or not, however if a user tries to resubmit the form after an alert is displayed, the recognised state fails to update. Is a loop of some kind needed?
function checkForm()
{
var x=document.forms["sdcomp"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var x=document.forms["sdcomp"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if (document.getElementById("questionone").checked==false)
{
alert("Question one must be completed");
return false;
}
if (document.getElementById("questiontwo").checked==false)
{
alert("Question two must be completed");
return false;
}
if (document.getElementById("questionthree").checked==false)
{
alert("Question three must be completed");
return false;
}
if (document.getElementById("questionfour").checked==false)
{
alert("Question four must be completed");
return false;
}
}
Example of the form's first question:
<tr>
<td class="question" colspan="4"><p class="question">Usain Bolt is the current world record holder for the men's 100 meters, but what is his best time?</p></td>
</tr>
<tr>
<td class="answer">8.45 seconds<input type="radio" value="Aone" name="Qone" id="questionone"></td>
<td class="answer">9.58 seconds<input type="radio" value="Atwo" name="Qone" id="questionone"></td>
<td class="answer">10.12 seconds<input type="radio" value="Athree" name="Qone" id="questionone"></td>
<td class="answer">9.32<input type="radio" value="Afour" name="Qone" id="question one">
</td>
</tr>
*****UPDATE new code below:************
<link rel="stylesheet" href="style.css" type="text/css">
<!-- inclusion of fb config -->
<?php require_once('config.php'); ?>
<!-- client side validation for text fields -->
<script language="JavaScript" type="text/javascript">
function checkForm()
{
var x=document.forms["sdcomp"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var x=document.forms["sdcomp"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
/* HERE */
function isAnswered(name) {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if ((input.name === name) && (input.checked)) {
return true;
}
}
return false;
}
if (!isAnswered("Qone")) {
alert("Question one must be completed");
return false;
}
if (!isAnswered("Qtwo")) {
alert("Question two must be completed");
return false;
}
if (!isAnswered("Qthree")) {
alert("Question three must be completed");
return false;
}
if (!isAnswered("Qfour")) {
alert("Question four must be completed");
return false;
}
}
</script>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sdfbcomp", $con);
// some code
?>
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$Qone = $_POST["Qone"];
$Qtwo = $_POST["Qtwo"];
$Qthree = $_POST["Qthree"];
$Qfour = $_POST["Qfour"];
?>
</head>
<body>
<div id="tablediv">
<table id="comptable">
<form name="sdcomp" method="post" action="insert.php" onSubmit="return checkForm();">
<tr class="userdetailfields">
<p>Name:</p><input type="text" size="12" maxlength="12" name="name"></br>
</tr>
<tr class="userdetailfields">
<p>Email:</p><input type="text" size="12" maxlength="30" name="email"></br>
</tr>
<tr>
<td class="question" colspan="4"><p class="question">Usain Bolt is the current world record holder for the men's 100 meters, but what is his best time?</p></td>
</tr>
<tr>
<td class="answer">8.45 seconds<input type="radio" value="Aone" name="Qone" id="questionone"></td>
<td class="answer">9.58 seconds<input type="radio" value="Atwo" name="Qone" id="questionone"></td>
<td class="answer">10.12 seconds<input type="radio" value="Athree" name="Qone" id="questionone"></td>
<td class="answer">9.32<input type="radio" value="Afour" name="Qone" id="question one"> </td>
</tr>
<tr>
<td class="question" colspan="4"><p class="question">Question two:</p></td>
</tr>
<tr>
<td class="answer">Answer one<input type="radio" value="Bone" name="Qtwo" id="questiontwo"></td>
<td class="answer">Answer two<input type="radio" value="Btwo" name="Qtwo" id="questiontwo"></td>
<td class="answer">Answer three<input type="radio" value="Bthree" name="Qtwo" id="questiontwo"></td>
<td class="answer">Answer four<input type="radio" value="Bfour" name="Qtwo" id="questiontwo"></td>
</tr>
<tr>
<td class="question" colspan="4"><p class="question">Question three:</td></p>
</tr>
<tr>
<td class="answer">Answer one<input type="radio" value="Cone" name="Qthree" id="questionthree"></td>
<td class="answer">Answer two<input type="radio" value="Ctwo" name="Qthree" id="questionthree"></td>
<td class="answer">Answer three<input type="radio" value="Cthree" name="Qthree" id="questionthree"></td>
<td class="answer">Answer four<input type="radio" value="Cfour" name="Qthree" id="questionthree"></td>
</tr>
<tr>
<td class="question" colspan="4"><p class="question">Question four:</td></p>
</tr>
<tr>
<td class="answer">Answer one<input type="radio" value="Done" name="Qfour" id="questionfour"></td>
<td class="answer">Answer two<input type="radio" value="Dtwo" name="Qfour" id="questionfour"></td>
<td class="answer">Answer three<input type="radio" value="Dthree" name="Qfour" id="questionfour"></td>
<td class="answer">Answer four<input type="radio" value="Dfour" name="Qfour" id="questionfour"></td>
</tr>
<tr><td><input type="submit" value="submit" name="submit" id="submit"><br /></td></tr>
</form><br />
</table>
</div>
</body>
Still have an issue with this, could you possibly help me? Thanks again!
Firstly, in your question, all the answers have the same id='questionone'. You need to remove these ids.
To check if a particular name group is checked you can use:
function isAnswered(name) {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if ((input.name === name) && (input.checked)) {
return true;
}
}
return false;
}
You can then test each question group with the following code:
if (!isAnswered("Qone")) {
alert("Question one must be completed");
return false;
}
Can you show the whole form? In the meantime, try this:
function checkForm() {
var x=document.forms["sdcomp"]["name"].value;
if (x==null || x=="") {
alert("Name must be filled out");
return false;
}
var x=document.forms["sdcomp"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Please enter a valid e-mail address");
return false;
}
if (document.getElementById("questionone").checked) {
alert("Option one is selected");
} else if (document.getElementById("questiontwo").checked) {
alert("Option two is selected");
} else if (document.getElementById("questionthree").checked) {
alert("Option three is selected");
} else if (document.getElementById("questionfour").checked) {
alert("Option four is selected");
} else {
alert("No option is selected");
}
}
And this is what i'm trying to tell you, put unique id's on your inputs to get their values in the function:
<tr>
<td class="answer">
<label>8.45 seconds</label>
<input type="radio" value="Aone" name="Qone" id="questionone" />
</td>
<td class="answer">
<label>9.58 seconds</label>
<input type="radio" value="Atwo" name="Qtwo" id="questiontwo" />
</td>
<td class="answer">
<label>10.12 seconds</label>
<input type="radio" value="Athree" name="Qthree" id="questionthree" />
</td>
<td class="answer">
<label>9.32 seconds</label>
<input type="radio" value="Afour" name="Qfour" id="questionfour" />
</td>
</tr>
Related
I have a registration form which SHOULD check the inputting data according to each function i have created(inside validation.js file) and after everything is ok then it should return all the data to the .php file which will save inthe phpmyadmin database.
However it is not working
Test1: validation is working (alone not included the action=.php)
Test2: without validation the data is storing in the database(phpmyadmin)
Test3: with validation and with action=.php) its not working the validation part
Please help me.
function formValidation()
{
var id = document.registration.nic;
var registerno = document.registration.regno;
var name = document.registration.pname;
var paddress = document.registration.address;
var maritial = document.registration.mars;
var religion = document.registration.rel;
var addname = document.registration.fhn;
var pcity = document.registration.city;
var telephone = document.registration.tel;
var age = document.registration.ag;
var gender = document.registration.gen;
if(ValidateNIC(id)) //done
{
if(allLettername(name)) //done
{
if(allnumericreg(registerno))
{
if(alphanumericpaddress(paddress)) //done
{
if(maritialselect(maritial)) //done
{
if(religionselect(religion)) //done
{
if(allLetteraddname(addname)) //done
{
if(alphanumericpcity(pcity)) //done
{
if(allnumerictel(telephone)) //done
{
if(allnumericage(age)) //done
{
if(genderselect(gender)) //done
{
}
}
}
}
}
}
}
}
}
}
}
return false;
}
function allLettername(name)
{
var letters = /^[A-Za-z ]+$/;
if(name.value.match(letters))
{
return true;
}
else
{
alert('Patient Name must have alphabet characters only');
return false;
}
}
function allLetteraddname(addname)
{
var letters = /^[A-Za-z ]+$/;
if(addname.value.match(letters))
{
return true;
}
else
{
alert('Father or Husband"s Name must have alphabet characters only');
return false;
}
}
function maritialselect(maritial)
{
if(maritial.value == "Default")
{
alert("Select your Maritial Status from the list");
return false;
}
else
{
return true;
}
}
function ValidateNIC(id)
{
var letters = /^[0-9a-zA-Z ]+$/;
if ((id.value.length == 10) && id.value.match(letters))
{
return true;
}
else
{
alert("NIC must contain alphanumeric characters only and must be 10 charators long!");
id.focus();
return false;
}
}
function alphanumericpaddress(paddress)
{
var letters = /^[0-9a-zA-Z ]+$/;
if(paddress.value.match(letters))
{
return true;
}
else
{
alert('Patient address must have alphanumeric characters only');
paddress.focus();
return false;
}
}
function alphanumericpcity(pcity)
{
var letters = /^[0-9a-zA-Z ]+$/;
if(pcity.value.match(letters))
{
return true;
}
else
{
alert('User City must have alphanumeric characters only');
pcity.focus();
return false;
}
}
function religionselect(religion)
{
if(religion.value == "Default")
{
alert("Select your Religion from the list");
return false;
}
else
{
return true;
}
}
function allnumericreg(registerno)
{
var numbers = /^[0-9]+$/;
if(registerno.value.match(numbers))
{
return true;
}
else
{
alert("Register No Must have numeric characters only");
return false;
}
}
function allnumerictel(telephone)
{
var numbers = /^[0-9]+$/;
if((telephone.value.length == 10) && telephone.value.match(numbers))
{
return true;
}
else
{
alert("Telephone Number must have numeric characters only and Length should 10 charators long! ");
return false;
}
}
function allnumericage(age)
{
var numbers = /^[0-9]+$/;
if(age.value.match(numbers))
{
return true;
}
else
{
alert("Age must have numeric characters only");
return false;
}
}
function genderselect(gender)
{
if(gender.value == "Default")
{
alert("Select your Gender from the list");
return false;
}
else
{
alert('Registration Form Successfully Submitted');
window.location.reload()
return true;
}
}
<?php
$con= mysqli_connect ("localhost","root","","hmsjason");
if (mysqli_connect_error()){
echo"Failed to Connect";
}
$sql="INSERT INTO patient(P_NIC,Reg_No,Full_Name,Address,Maritial_Sts,Religion,DOB,H_F_Name,City,Contact,Age,Gender,Room_No)VALUES('$_POST[nic]','$_POST[regno]','$_POST[pname]','$_POST[address]','$_POST[mars]','$_POST[rel]','$_POST[dob]','$_POST[fhn]','$_POST[city]','$_POST[tel]','$_POST[ag]','$_POST[gen]','$_POST[room]')";
if(!mysqli_query($con,$sql)){
die("Error".mysqli_error($con));
}
mysqli_close($con);
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header("location:reception.html");
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="style1.css">
<script src="regvalidation.js"></script>
</head>
<body>
<br><br><br>
<table background="Images/formbg1.jpg" border="2" align="center" width ="825" height="820" >
<th align=center valign=center>
<form action="patientdetails.php" method="POST"/>
<!--form name='registration' onSubmit="return formValidation()"/>-->
<div class="textcenter1">
<h2>Patient Registration Form</h2>
</div>
<br><br>
<table border="0"; align="center" width ="655" height="550" >
<tr>
<td>
NATIONAL ID :</td><td><input type="text" name="nic" size="40" />
</td>
</tr>
<tr>
<td>
<b>
REGISTRATION NUMBER :</td><td><input type="text" name="regno" size="40" />
</td>
</tr>
<tr>
<td>
PATIENT NAME :</td><td><input type="text" name="pname" size="40" />
</td>
<tr>
<td>
PATIENT ADDRESS :</td><td><input type="text" name="address" size="40" />
</td>
</tr>
<tr>
<td>
Maritial Status: :</td>
<td>
<select name="mars">
<option selected="" value="Default">(Please select your Status)</option>
<option value="Maried">Married</option>
<option value="Unmarried">UnMarried</option>
</select>
</td>
</tr>
<tr>
<td>
RELIGION :</td>
<td>
<select name="rel">
<option selected="" value="Default">(Please select your Religion)</option>
<option value="Buddhist">Buddhist</option>
<option value="Catholic">Catholic</option>
<option value="Christian">Christian</option>
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Others">Others</option>
</select>
</td>
</tr>
<tr>
<td>
Date of Birth: </td><td><input type="date" name="dob">
<td>
</tr>
<tr>
<td>
FATHER'S NAME/HUSBAND'S NAME :</td><td><input type="text" name="fhn" size="40" />
</td>
</tr>
<tr>
<td>
CITY :</td><td><input type="text" name="city" size="40" />
</td>
</tr>
<tr>
<td>
TELEPHONE NUMBER/MOBILE NUMBER :</td><td><input type="text" name="tel" size="40" />
</td>
</tr>
<tr>
<td>
AGE :</td><td><input type="text" name="ag" size="40" />
</td>
</tr>
<tr>
<td>
Gender :</td>
<td>
<select name="gen">
<option selected="" value="Default">(Please select your Gender)</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr>
<td>
Room: </td><td><input type="text" name="room">
<td>
</tr>
</b>
<tr>
<td></td>
<td>
<input align="left" type="image" src="Images/submit.png" alt="Submit" name="submit" value="Submit" width="115" height="57"/>
</form>
<!--if submit button and reset button in same <form> will perform the formvalidation which leds the reset buttton also work as a submit button(wont reset anyting)-->
<form><input align="center" type="image" src="Images/reset.png" alt="Reset" name="reset" value="reset" width="115" height="57"/>
</td>
</tr>
</form>
</table>
</th>
</table>
<br><br>
</body>
</html>
It appears your validation method always returns false. If the code called by onSubmit returns false, the action will not be executed. The same is true for onclick and other event functions.
Once you've evaluated all the conditions to be valid, you should return true to tell the form that it can take over and do its thing.
I have a simple form that asks for Name, Email, Phone Number, Age and Income. When I hit submit, the validateForm function is supposed to check for errors and if there are any errors the textbox will be red and there will be a red error message display under the form. The function doesn't seem to be working at all and I'm not sure why.
This is my form and script. I tried setting the submit button to have an onclick event to call the function but that didn't work either.
<script>
function validateForm() {
if (document.forms.formValidation.Name.value == "") {
document.getElementById("error").style.display = "inline";
document.forms.formValidation.getElementById("name").style.backgroundColor = "red";
return false;
}
if (document.forms.formValidation.email.value == "") {
document.getElementById("error").style.display = "inline";
document.forms.formValidation.email.style.backgroundColor = "red";
}
var phoneNo = /^\d{10}$/;
if (document.forms.formValidation.number.value.match(phoneNo)) {
return true;
}
else {
document.getElementById("error").style.display = "inline";
document.forms.formValidation.number.style.backgroundColor = "red";
return false;
}
var emailVal = document.formValidation.email.value;
ampersandPos = emailVal.indexOf("#");
dotPos = emailVal.lastIndexOf(".");
if (amersandPos < 1 || (dotPos - amersandPos < 2)) {
alert("Please enter a valid email address.");
document.getElementById("error").style.display = "inline";
return false;
}
return true;
var len = age.length;
for (var i = 0; i < len; i++) {
if (document.forms.formValidation.age[i].checked)
{
return true;
}
else {
document.getElementById("error").style.display = "inline";
return false;
}
}
}
</script>
<form name="formValidation" onsubmit="return validateForm()">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">First and Last Name: </td>
<td align="left"><input type="text" id="name" name="Name" ></td>
</tr>
<tr>
<td align="right">Email: </td>
<td align="left"><input type="text" id="email" name="email" ></td>
</tr>
<tr>
<td align="right">Phone Number: </td>
<td align="left"><input type="text" name="number" /></td>
</tr>
<tr>
<td align="right">Age:</td>
<td class="rad"><input type="radio" name="age" value="minor">Under 18</td>
<td class="rad"><input type="radio" name="age" value="adult">18-64</td>
<td class="rad"><input type="radio" name="age" value="senior">65+</td>
</tr>
<tr>
<td align="right">Income:</td>
<td>
<select>
<option value="underFifty">Under $50,000</option>
<option value="fiftyToHundred">$50,000 - $100,000</option>
<option value="overHundred">Over $100,000</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
<div id="error">
<p>Required fields are missing!</p>
</div>
You are missing a closing parenthesis on this line:
if (amersandPos < 1 || (dotPos - amersandPos < 2)
Also, this line is not valid:
document.formValidation.email.style.background-color = "red";
Because background-color is not a valid identifier name.
Here's a fiddle with these and the one issue in the comment fixed: https://jsfiddle.net/0zyv3g98/
You have mistakes in you js. you cannot use document.formValidation.name or something like that. the correct syntax is `document.forms.formValidation. Correction all your code and it will work.
if (document.forms.formValidation.Name.value == "") {
document.forms.formValidation.getElementById("error").style.display = "inline";
document.forms.formValidation.getElementById("name").style.backgroundColor = "red";
//return false;
}
if (document.forms.formValidation.email.value == "") {
document.forms.formValidation.getElementById("error").style.display = "inline";
document.forms.formValidation.email.style.backgroundColor = "red";
}
var emailVal = document.forms.formValidation.email.value;
ampersandPos = emailVal.indexOf("#");
dotPos = emailVal.lastIndexOf(".");
if (amersandPos < 1 || (dotPos - amersandPos < 2)
{
alert("Please enter a valid email address.");
document.forms.formValidation.getElementById("error").style.display = "inline";
return false;
}
return true;
There is something not working at this script.
I need when check one radio button to add the amount at the total price.
This is doing well, but if I check different radio buttons, it ads all of them.
If I have total = 100$; and button1=10$, button2=10$, button3=10$
and if I check all 3... I will get total = 130$ instead of 110$
function calculateTotal(payment)
{
var check=document.getElementById("check").value;
var city = document.getElementsByName('loc');
var value= payment.value;
var total= document.getElementById("totl").value;
var tcharge;
var pvcharge=document.getElementById("ch").value;
if(value==0 && check==0)
return;
if(value==0 && check==1)
{
total= parseFloat(parseFloat(total)-parseFloat(pvcharge)).toFixed(2);
tcharge=0;
}else
{
if(total>=200)
return;
if(value=='online' || value =='transfer_bancar' || value=='cash' || value == 'la_sediul_nostru')
{
if(city[0].checked)
{
total= parseFloat(parseFloat(total)+15.0).toFixed(2);
tcharge=15.00;
}
else
if(city[1].checked)
{
total= parseFloat(parseFloat(total)+30.0).toFixed(2);
tcharge=30.00;
}
}
else
if(value='la_expeditor')
{
if(city[0].checked)
{
total= parseFloat(parseFloat(total)+30.0).toFixed(2);
tcharge=30.00;
}
else
if(city[1].checked)
{
total= parseFloat(parseFloat(total)+60.0).toFixed(2);
tcharge=60.00;
}
}
}
document.getElementById("tot").innerHTML=total+" LEI";
document.getElementById("totl").value=total;
document.getElementById("amt").value=total;
document.getElementById("tcharge").innerHTML=tcharge+" LEI";
document.getElementById("check").value=1;
document.getElementById("ch").value=tcharge;
}
radio box
<tr>
<td colspan="2"> <input type="radio" name="payment" value="online" id="online" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdad</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="transfer_bancar" id="bancar" onClick="calculateTotal(this); return bancarval();" /> <span class="fontext"><b>asdadadadasd</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="cash" onClick="calculateTotal(this);return empty();" /> <span class="fontext"><b>asdadadadadad</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="la_expeditor" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdadad</span></td> </tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="la_sediul_nostru" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdad</b></span></td>
</tr>
<tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="0" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdasdasd</b></span></td> </tr>
<tr>
<td><span class="fontext"><b>Cost transport: </b></span></td> <td><span class="fontext" ><b id="tcharge">0.00 LEI</b></span></td> </tr>
and php
if($Tott<200)
if(isset($_POST['loc']))
{
$tcharges=$_POST['loc'];
if(isset($_POST['payment']))
{
$payment=$_POST['payment'];
if($payment!=0)
if($payment=='online' || $payment =='transfer_bancar' || $payment=='cash' || $payment == 'la_sediul_nostru')
{
if($tcharges=='in')
$Tott+=15;
else
$Tott+=30;
}else
if($payment=='la_expeditor')
{
if($tcharges=='in')
$Tott+=30;
else
$Tott+=60;
}
}
}
Each time, you're operating off the total of the previous calculation.
Offending line:
var total= document.getElementById("totl").value;
Instead, change it to operate off the original, clean value.
I have a html code saved as a php, the form validation works in google chrome but not in IE. In IE after I hit the submit button, the page automatically goes to process form regardless of errors.
This is my code:
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validateForm() {
var errors = 0;
var fName = document.forms["orderForm"].firstName.value;//first name validation
if (fName == null || fName == "")
{
document.getElementById('firstNameError').innerHTML = "Please enter a first name.";
errors++;
} else {
document.getElementById('firstNameError').innerHTML = "";
}
//var lName = document.forms["orderForm"].lastName.value;//last name validation
if (lName == null || lName == "")
{
document.getElementById('lastNameError').innerHTML = "Please enter a last name.";
errors++;
} else {
document.getElementById('lastNameError').innerHTML = "";
}
//var address = document.forms["orderForm"].address.value;//address validation
if (address == null || address == "")
{
document.getElementById('addressError').innerHTML = "Please enter an address.";
errors++;
} else {
document.getElementById('addressError').innerHTML = "";
}
//var city = document.forms["orderForm"].city.value;//city validation
if (city == null || city == "")
{
document.getElementById('cityError').innerHTML = "Please enter a city.";
errors++;
} else {
document.getElementById('cityError').innerHTML = "";
}
//var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if (pCodeCheck)
{
document.getElementById('postalCoderror').innerHTML = "";
}
else
{
document.getElementById('postalCoderror').innerHTML = "Please enter a valid postal code.";
errors++;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if (itemQTY < 0)
{
document.getElementById('qtyError').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError').innerHTML = "";
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if (itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError2').innerHTML = "";
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if (itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError3').innerHTML = "";
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if (wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML = "You must order atleast one item.";
errors++;
} else {
document.getElementById('itemQTY').innerHTML = "";
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3);
alert('Your total is: $' + total4 + '.00');
return errors;
}
function startValidate() {
var errors = validateForm();
if (errors == 0) {
document.forms['orderForm'].submit();
} else {
return false;
}
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" action="processForm.html" onsubmit="return startValidate()">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Quebec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order">
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
When you look at the console in IE’s developer tools (F12), you will see that there is an error message about undeclared variable lName. This causes the error checking to be aborted.
You have several lines like
//var lName = document.forms["orderForm"].lastName.value;//last name validation
Since // starts a comment in JavaScript, the line has no effect. The variable lName is not declared or defined elsewhere either.
So you need to remove those // comment starters. Note that the code does not work in Chrome either; you may have tested a different version in Chrome, or misinterpreted some behavior.
In the console, you can also see a message for line 237 about “unexpected identifier”. It is actually a serious HTML markup error; IE reports some of such errors, in a strange way. The error is that a tr element has an input element as child, which is forbidden in HTML syntax. This is why the Submit Order and Reset Form appear on top of each other and not on the same row as intended. (For usability, the Reset Form button should be removed, but I digress.)
I have all of my validation code figured out but I'm not quite sure on how to code an alert to pop up before the form is submitted but after the validation is complete.
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validate()
{
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
/*
// trying to send alert with the order total.
// not sure how to call it after the validation is done.
var total1;
var total2;
var total3:
var total4;
if(document.getElementById('widget1qty').value == 0)
{
total1 = 0;
}
else(document.getElementById('widget1qty').value != 0)
{
total1 = document.getElementById('widget1qty').value * 5;
}
if(document.getElementById('widget2qty').value == 0)
{
total2 = 0;
}
else(document.getElementById('widget2qty').value != 0)
{
total2 = document.getElementById('widget2qty').value * 15;
}
if(document.getElementById('widget3qty').value == 0)
{
total3 = 0;
}
else(document.getElementById('widget3qty').value != 0)
{
total3 = document.getElementById('widget3qty').value * 25;
}
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
*/
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" onsubmit="validate();" action="processForm.html">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Québec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr></tr><tr></tr><tr></tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<td><input type="submit" name="btnSubmit" id="btnSubmit" onclick="return validate();" value="Submit Order"></td>
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
I just don't know how to code it to pop up after the validation is complete.
In your form, you could put anid = "myForm"and then do this in javascript:
function validateForm() {
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
return;
}
function startValidate(){
validateForm();
document.forms['orderForm'].submit();
}
Edit:
Just add all the other info in the validateForm() function.
I did't seen it because I started my edit before you added the HTML and the other JS.
According to War10ck's post you should change this :
<input type="submit" name="btnSubmit" id="btnSubmit" onsubmit="startValidate()" value="Submit Order">
You can make another function called FireOnSubmit and do something like this:
`
function FireOnSubmit(){
if(validate()==true) alert(""form validated..is being redirected")
else {
alert("invalid form data");
return false;
}
}
`
You can put FireOnSubmit on the onsubmit of the form instead of the validate function.
Also, you will need to return true or false from your validate function.
Instead of all that JavaScript, this should work just as well.
The submit button cannot be clicked until all fields you pick have been filled.
Then a alert pops up with your message.
This Goes In The Head Section
<script>
function checkform()
{
var f = document.forms["testform"].elements;
var cansubmit=true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length==0) cansubmit=false;
}
if (cansubmit)
{
document
.getElementById('submit'
).disabled=false;
}
}
</script>
Here Is The Form. The Submit Button Is Disabled Until All Fields Are Filled.
<form name="testform">
<input type="text" onKeyup="checkform()" placeholder="First Name"required/><br>
<input type="text" onKeyup="checkform()" placeholder="Last Name" required/><br>
<input id="submit" type="submit" disabled="disabled" value="Submit" onclick="alert('Your Alert Here...')"/>
</form>