Field Update Javascript - javascript

When the menu is selected from the radio buttons, and the amount of guests, the total price should be updated. But couldn't find the issue in the code. It is not updating.
When menu is clicked AND Amount of guests => Total Price update.
var proceed = 0;
var myTea = "";
var chosenTea;
function getSelectedText(selectList) {
return selectList.options[selectList.selectedIndex].text;
}
function getRadioValue(radioArray) {
var i;
for (i = 0; i < radioArray.length; i++) {
if (radioArray[i].checked)
return radioArray[i].value;
}
return "";
}
function getSelectedValue(selectList) {
return selectList[selectList.selectedIndex].value;
}
function view(form) {
var termsconds = form.terms.value;
var tea = getRadioValue(form.teaChoice);
var nb_people = getSelectedText(form.size);
var multiplier = parseInt(getSelectedValue(form.size));
var allergies = form.allergies.value;
var champagne = form.champ.value;
var champText = "";
var special;
if (champagne = true) {
special = 10;
champText = "with champagne";
} else {
special = 0;
champText = "";
}
var teaprice;
if (tea !== null) {
teaprice = parseInt(tea)
} else {
teaprice = 0;
}
var totalprice;
var additional;
var totalOrder;
totalprice = (teaprice + special) * multiplier;
if (allergies !== null) {
additional = "allergies to: " + allergies;
} else {
additional = " no food allergy ";
}
form.price.value = totalprice;
if (proceed === 1) {
if (termsconds === false) {
alert("you must read the terms and conditions");
} else {
if (myTea === null) {
alert("You must choose tea before you can proceed with order");
proceed = 0;
} else {
totalOrder = "you have ordered a " + chosenTea + champText + "for " + nb_people + " and we have" +
"noted that you have " + additional + ".\nYour toal bill is \u00A3" + totalprice + ".\n";
confirm(totalOrder);
proceed = 0;
}
}
}
}
function displayTea(teaName) {
myTea = document.getElementById("chosenTea");
myTea.value = teaName;
chosenTea = teaName;
}
body {
color: #FFFFFF;
}
h1 {
font-family: "corsoiva", serif;
color: #005080;
font-size: 40px;
}
#myTable {
background-color: #50a0d0;
}
.myBlue {
color: #005080;
}
.myWhite {
background-color: #FFFFFF;
}
.toRight {
float: right;
text-align: right;
}
<center>
<h1>Welcome to Web Tech's Afternoon tea</h1>
<form>
<table border="5" cellpadding="10" cellspacing="5" id="myTable">
<tr>
<td colspan="2" align="center">
<h2>Please chosse from the menu below <br> and select the number of people </h2>
</td>
</tr>
<tr>
<td colspan="2" class="myWhite">
<span class="myBlue">Please select your menu:</span><br>
<input type="radio" name="teaChoice" value="20" onclick="displayTea('Easter AFternoon Tea');view(this.form)">
<input type="radio" name="teaChoice" value="30" onclick="displayTea('Pastries and specialist');view(this.form)">
<input type="radio" name="teaChoice" value="15" onclick="displayTea('Traditional Afternoon Tea');view(this.form)">
<br>
<span class="myBlue">Your tea: </span>
<input type="text" id="chosenTea" size="50">
</td>
</tr>
<tr>
<td colspan="2">
<div align="left">Please select party size and champagne option: <br><br>
<select name="size" onclick="view(this.form)">
<option value="1">1 guest </option>
<option value="2">2 guest </option>
<option value="3">3 guest </option>
<option value="4">4 guest </option>
</select>
<input type="checkbox" name="champ" value="champagne" onclick="view(this.form)">with champagne</div>
<div class="toRight">Please enter food allergies in the input field below: <br>
<input type="text" name="allergies" size="60"></div>
</td>
</tr>
<tr>
<td><b>Total price:$</b><input type="text" name="price" size="4"></td>
<td rowspan="2" align="center"><br><br>
<input type="button" name="proceedOrder" value="Proceed with order" onclick="view(this.form);return view(this.form)">
</td>
</tr>
<tr>
<td><input type="checkbox" name="terms " value="read"> I have read and accepted the <a href="Terms.html">terms and
conditions</a>
</td>
</tr>
</table>
</form>
</center>

There is a space in your HTML at name="terms ": remove it. Then form.terms will be valid in your code.
You could have spotted this if you would have checked the console for errors, as in your current version the following line:
var termsconds = form.terms.value;
... produces:
form.terms is undefined

Related

Alert to stop duplicate data

I am trying to add an alert to notify the user that data has already been entered. I want to apply this to the flight number only. So that when a user types in an already typed flight number and saves it into the array it will pop up a message telling them that it has already been posted.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>
I am also trying to highlight the member table to show which group they are in based on total miles. I would like for the color of the highlight to match the member level. Something kind of like this:
<style>
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
function highlightWeightClass(total-miles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = total-miles< 10000 ? "bronze" : "";
rows[1].className = total-miles >= 10000 && total-miles < 25000 ? "silver" : "";
rows[2].className = total-miles >= 25000 ? "gold" : "";
</script>
For checking if an Array contains on Object, use this:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
For highlighting the member table: add an event listener for document.getElementById("Miles")'s keyup and execute your function then.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
Array.prototype.contains = function(obj) {//function to check if an Array contains an object
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
function highlightWeightClass(totalmiles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = totalmiles< 10000 ? "bronze" : "";
rows[1].className = totalmiles >= 10000 && totalmiles < 25000 ? "silver" : "";
rows[2].className = totalmiles >= 25000 ? "gold" : "";
}
</script>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
if(!FlightNumber.contains(FlightNumberValue)){
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
} else {
alert("You have already entered this flight number.");
}
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
window.onload = function(){
document.getElementById("Miles").addEventListener("keyup", function(event){
highlightWeightClass(document.getElementById("Miles").value);
});
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>

How to determine how many years (D/M/Y) left from the Birthday to a certain age in age calculator?

What should I need to change to determine how many years (D/M/Y) left from the Birthday to a certain age? i.e my birthday is 01.01.1990 and and today my age is 27 Years, 5 month.... and I will 50 years old in 2040.
I want to know How many years left (DD/M/Y) from today to become 50 years old?
Another thing is Concern title should be just above the result not left side of the result.
Code below for this script and and two picture regarding this..
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function wr_document()
{
var w=new Date();
var s_d=w.getDate();
var s_m=w.getMonth()+1;
var s_y=w.getFullYear();
document.cir.len11.value=s_d;
document.cir.len12.value=s_m;
document.cir.len13.value=s_y;
}
function isNum(arg)
{
var args = arg;
if (args == "" || args == null || args.length == 0)
{
return false;
}
args = args.toString();
for (var i = 0; i<args.length; i++)
{
if ((args.substring(i,i+1) < "0" || args.substring(i, i+1) > "9") && args.substring(i, i+1) != ".")
{
return false;
}
}
return true;
}
function checkday(aa)
{
var val = aa.value;
var valc = val.substring(0,1);
if(val.length>0 && val.length<3)
{
if(!isNum(val) || val == 0)
{
aa.value="";
}
else if( val < 1 || val > 31)
{
aa.value=valc;
}
}
else if(val.length>2)
{
val = val.substring(0, 2);
aa.value=val;
}
}
function checkmon(aa)
{
var val = aa.value;
var valc = val.substring(0,1);
if(val.length>0 && val.length<3)
{
if(!isNum(val) || val == 0)
{
aa.value="";
}
else if(val < 1 || val > 12)
{
aa.value=valc;
}
}
else if(val.length>2)
{
val = val.substring(0, 2);
aa.value=val;
}
}
function checkyear(aa)
{
var val = aa.value;
var valc = val.substring(0,(val.length-1));
if(val.length>0 && val.length<7)
{
if(!isNum(val) || val == 0)
{
aa.value=valc;
}
else if(val < 1 || val>275759)
{
aa.value="";
}
}
else if(val.length>4)
{
aa.value=valc;
}
}
function checkleapyear(datea)
{
if(datea.getYear()%4 == 0)
{
if(datea.getYear()% 10 != 0)
{
return true;
}
else
{
if(datea.getYear()% 400 == 0)
return true;
else
return false;
}
}
return false;
}
function DaysInMonth(Y, M) {
with (new Date(Y, M, 1, 12)) {
setDate(0);
return getDate();
}
}
function datediff(date1, date2) {
var y1 = date1.getFullYear(), m1 = date1.getMonth(), d1 = date1.getDate(),
y2 = date2.getFullYear(), m2 = date2.getMonth(), d2 = date2.getDate();
if (d1 < d2) {
m1--;
d1 += DaysInMonth(y2, m2);
}
if (m1 < m2) {
y1--;
m1 += 12;
}
return [y1 - y2, m1 - m2, d1 - d2];
}
function calage()
{
var curday = document.cir.len11.value;
var curmon = document.cir.len12.value;
var curyear = document.cir.len13.value;
var calday = document.cir.len21.value;
var calmon = document.cir.len22.value;
var calyear = document.cir.len23.value;
if(curday == "" || curmon=="" || curyear=="" || calday=="" || calmon=="" || calyear=="")
{
alert("Please fill all the values and click 'Go'");
}
else if(curday == calday && curmon==calmon && curyear==calyear)
{
alert("Today your birthday & Your age is 0 years old")
}
else
{
var curd = new Date(curyear,curmon-1,curday);
var cald = new Date(calyear,calmon-1,calday);
var diff = Date.UTC(curyear,curmon,curday,0,0,0)
- Date.UTC(calyear,calmon,calday,0,0,0);
var dife = datediff(curd,cald);
document.cir.val.value=dife[0]+" years, "+dife[1]+" months, and "+dife[2]+" days";
var secleft = diff/1000/60;
document.cir.val3.value=secleft+" minutes since your birth";
var hrsleft = secleft/60;
document.cir.val2.value=hrsleft+" hours since your birth";
var daysleft = hrsleft/24;
document.cir.val1.value=daysleft+" days since your birth";
//alert(""+parseInt(calyear)+"--"+dife[0]+"--"+1);
var as = parseInt(calyear)+dife[0]+1;
var diff = Date.UTC(as,calmon,calday,0,0,0)
- Date.UTC(curyear,curmon,curday,0,0,0);
var datee = diff/1000/60/60/24;
document.cir.val4.value=datee+" days left for your next birthday";
}
}
function color(test)
{
for(var j=7; j<12; j++)
{
var myI=document.getElementsByTagName("input").item(j);
//myI.setAttribute("style",ch);
myI.style.backgroundColor=test;
}
}
function color1(test)
{
var myI=document.getElementsByTagName("table").item(0);
//myI.setAttribute("style",ch);
myI.style.backgroundColor=test;
}
</script>
<style media="screen" type="text/css">
.cal-container {
width: 540px;
margin: 10px auto 0;
}
#age-calculator {
background: none repeat scroll 0 0 #DDDDDD;
border: 1px solid #BEBEBE;
padding-left: 20px;
}
.calc {
border-color: #AAAAAA #999999 #929292 #AAAAAA;
border-style: solid;
border-width: 1px 2px 2px 1px;
padding: 2px 30px 3px;
height: 27px;
}
.calc:active {
border-color: #AAAAAA #999999 #929292 #AAAAAA;
border-style: solid;
border-width: 1px;
}
</style>
<title>Age calculator</title>
</head>
<body onLoad="wr_document()">
<div class="cal-container">
<div id="calculator-container">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td valign="top">
<h1 style="padding-top: 10px;">Age Calculator</h1>
<div class="descalign">
<span>Calculate your age in days, years, minutes, seconds. Know how many days are left for your next birthday.</span><br/><br/>
</div>
<div id="age-calculator">
<table width="100%" cellspacing="4" cellpadding="0" border="0" bgcolor="">
<tbody>
<tr>
<td colspan="2">
<table class="result" width="100%" height="100%">
<tbody>
<tr>
<td>
<form name="cir">
<table cellspacing="0" cellpadding="3">
<tbody>
<tr>
<td colspan="2">
<br>
Today's Date is:
</td>
</tr>
<tr>
<td align="center" colspan="2">
Date -
<input class="innerc resform" type="text" value="" onkeyup="checkday(this)" size="2" name="len11">
Month -
<input class="innerc resform" type="text" value="" onkeyup="checkmon(this)" size="2" name="len12">
Year -
<input class="innerc resform" type="text" value="" onkeyup="checkyear(this)" size="4" name="len13">
<br>
<br>
</td>
</tr>
<tr>
<td colspan="2"> Enter Your Date of Birth : </td>
</tr>
<tr>
<td align="center" colspan="2">
Date -
<input class="innerc resform" type="text" onkeyup="checkday(this)" size="2" name="len21">
Month -
<input class="innerc resform" type="text" onkeyup="checkmon(this)" size="2" name="len22">
Year -
<input class="innerc resform" type="text" onkeyup="checkyear(this)" size="4" name="len23">
<br>
<br>
<input class="calc" type="button" onclick="calage()" value=" Go " name="but">
<br>
<br>
</td>
</tr>
<tr>
<td class="form" width="30%" align="center">
<b> </b>
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>
<b> Your Age is </b>
</td>
<td>
<input class="resform" type="text" readonly="" size="36" name="val">
</td>
</tr>
<tr>
<td>
<b> Your Age in Days </b>
</td>
<td>
<input class="resform" type="text" readonly="" size="36" name="val1">
</td>
</tr>
<tr>
<td>
<b> Your Age in Hours </b>
</td>
<td>
<input class="resform" type="text" readonly="" size="36" name="val2">
(Approximate)
</td>
</tr>
<tr>
<td class="form">
<b> Your Age in Minutes </b>
</td>
<td>
<input class="resform" type="text" readonly="" size="36" name="val3">
(Approximate)
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<b> Your Next Birthday</b>
</td>
<td>
<input class="innerc resform" type="text" readonly="" size="36" name="val4">
</td>
</tr>
</tbody>
</table>
</form>
</td>
</tr>
</tbody>
</table>
<br>
</td>
<td> </td>
</tr>
<tr>
<td align="right" colspan="2"> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
<br>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
There's a number of ways to achieve what you're asking.
For the formatting, you could define CSS rules for the table to be something like:
width: 100%;
text-align: center;
For the time until the 50th birthday, you could add 50 years in ms to the birth date and calculate accordingly, however you might need to be aware of the following in your calculations:
https://en.wikipedia.org/wiki/Year_2038_problem

Jquery return value from two change functions to calculate

I'm trying to create some calculation script. I have a form with some input fields. One is text and one are multiple radio buttons.
I want to change the price field according to the values which are set.
I got this working when I change the radio buttons in the table. However I'm stuck on how to multiple the value with the value from updateQuantity function. That function only works when I change the radio buttons again.
To make things clear I created a fiddle here.
My HTML
<form action="url" id="product_configure_form" method="post">
<span class="price"></span>
<table id="order" class="order">
...
<tbody>
<tr>
<td>
<input type="radio" id="product_configure_custom_123_456" name="custom[123]" value="somevalue" data-price="99.95">
</td>
</tr>
<tr>
<td>
<input type="radio" id="product_configure_custom_321_654" name="custom[321]" value="somevalue" data-price="199.95">
</td>
</tr>
</tbody>
</table>
<input type="text" name="quantity" value="1" />
<div class="change">
+
-
</div>
</form>
My Script
<script type="text/javascript">
function updateQuantity(way){
var quantity = parseInt($('.cart input').val());
if (way == 'up'){
if (quantity < 50){
quantity++;
} else {
quantity = 50;
}
} else {
if (quantity > 1){
quantity--;
} else {
quantity = 1;
}
}
$('.cart input').val(quantity);
}
function update_amounts() {
var price = $('#order').find('input[type="radio"]:checked').data('price');
var times = $('.cart input').val();
var value = (price * times).toFixed(2);
$('.price').text('€' + value);
}
$(document).ready(function(){
$("#product_configure_form").on("change", "#order input", update_amounts);
$(".cart input").on("change keyup paste", update_amounts);
});
</script>
Call update_amounts() on the end of your updateQuantity() function.
Or change it to this on the same line as I mentioned above:
$('.cart input').val(quantity).change();
Working Demo
function updateQuantity(way) {
var quantity = parseInt($('.cart input').val());
if (way == 'up') {
if (quantity < 50) {
quantity++;
} else {
quantity = 50;
}
} else {
if (quantity > 1) {
quantity--;
} else {
quantity = 1;
}
}
$('.cart input').val(quantity);
update_amounts()
}
function update_amounts() {
var price = $('#order').find('input[type="radio"]:checked').data('price');
var times = $('.cart input').val();
var value = (price * times).toFixed(2);
$('.price').text('€' + value);
}
$(document).ready(function() {
$("#product_configure_form").on("change", "#order input", update_amounts);
$(".cart input").on("change keyup paste", update_amounts);
});
table.order {
margin: 15px 0;
width: 100%;
}
.order th {
background: #eee none repeat scroll 0 0;
padding: 10px;
text-align: left;
}
.order td {
padding: 5px 10px;
}
.price{
background:#000;
color:#fff;
width:100px;
height:100px;
display:block;
text-align:center;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="url" id="product_configure_form" method="post">
<span class="price">bla</span>
<table id="order" class="order">
<thead>
<tr>
<th>title</th>
<th>price</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="radio" id="product_configure_custom_123_456" name="custom[123]" value="123456" data-price="99.95">
<label for="product_configure_custom_123_456">option a</label>
</td>
<td class="prijs">$99.95</td>
<tr>
<td>
<input type="radio" id="product_configure_custom_321_654" name="custom[123]" value="654321" data-price="199.95">
<label for="product_configure_custom_321_654">option b</label>
</td>
<td class="prijs">$199.95</td>
</tr>
</tbody>
</table>
<div class="cart">
<input type="text" name="quantity" value="1" />
<div class="change">
+
-
</div>
</div>
</form>

Javascript Onload expected object error

I'm getting "scrollingMsg" is undefined. It's not the cause though; it was functioning before I started doing the validSalesAmt() function. Beside that, not sure if this will help find the bug, but clicking the fields in the form gave an error saying that function wasn't defined. Please, no recommendations 'you can do it this way instead' because this is an assignment for school that has to be done as is in the textbook.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chapter 10 Shoreline State Bank</title>
<script type="text/javascript">
var adMsg = " **Did you know some used cars can have 100% loan value? Ask for details! **"
var beginPos = 0
function scrollingMsg()
{
msgForm.scrollingMsg.value=adMsg.substring(beginPos,adMsg.length)+adMsg.substring(0,beginPos)
beginPos=beginPos+1
if (beginPos>adMsg.length)
{
beginPos=0
}
window.setTimeout("scrollingMsg()",200)
}
var salesAmt
var loanAmt
var loanRate
var loanYears
function validSalesAmt()
{
var salesAmt=parseInt(homeLoanForm.SaleAmount.value,10)
if(isNaN(salesAmt)||(salesAmt <= 0))
{
alert("The sales price is not a valid number!")
homeLoanForm.SaleAmount.value = ""
homeLoanForm.SaleAmount.focus()
}
else
{
var downPmtAmt=parseInt(homeLoanForm.DownPayment.value, 10)
if(isNaN(downPmtAmt)||(downPmtAmt<=0)||(downPmtAmt>salesAmt))
{
alert("The down payment should be greater than 0 and less than the sales amount!")
homeLoanForm.DownPayment.value=""
homeLoanForm.DownPayment.focus()
}
else
{
loanAmt = salesAmt-downPmtAmt
homeLoanForm.LoanAmount.value=loanAmt
homeLoanForm.Rate.focus()
}
}
}
function CalcLoanAmt()
{
loanRate=parseFloat(homeLoanForm.Rate.value)
if (isNaN(loanRate) || (loanRate <= 0))
{
alert("The interest rate is not a valid number!")
homeLoanForm.Rate.value=""
homeLoanForm.Rate.focus()
}
else
{
loanYears=homeLoanForm.Years.value
if (isNaN(loanYears) || (loanYears < 1 || loanYears >30))
{
alert("Please select a valid number from the list (10,15,20, or 30)!")
homeLoanForm.Years.selectedIndex = 0
homeLoanForm.Years.focus()
}
else
{
var monthlyPmtAmt = monthlyPmt(loanAmt,loanRate,loanYears)
homeLoanForm.Payment.value=dollarFormat(monthlyPmtAmt.toString())
}
}
}
function monthlyPmt(loanAmt,loanRate,loanYears)
{
var interestRate = loanRate/1200
var Pmts = loanYears*12
var Amnt - loanAmt * (interestRate/(1-(1/Math.pow(1+interestRate,Pmts))))
return Amnt.toFixed(2)
}
function dollarFormat(valuein)
{
var formatValue= ""
var formatDollars= ""
formatAmt = valuein.split(".",2)
var dollars = formatAmt[0]
var dollarLen = dollars.length
if (dollarLen > 3)
{
while (dollarLen > 0)
{
tempDollars = dollars.substring(dollarLen - 3,dollarLen)
if(tempDollars.length == 3)
{
formatDollars = ","+tempDollars+formatDollars
dollarLen = dollarLen - 3
}
else
{
formatDollars = tempDollars+formatDollars
dollarLen = 0
}
}
if(formatDollars.substring(0,1) == ",")
{
dollars = formatDollars.substring(1,formatDollars.length)
}
else
dollars = formatDollars
}
var cents = formatAmt[1]
var formatValue="$"+dollars+"."+cents+
return formatValue
}
function popUpNotice()
{
open("chapter10-1notice.html","noticeWin","width-520,height=330")
}
function copyRight()
{
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
displayDateLast.innerHTML="<h6>Copyright© Shoreline State Bank"+"<br />This document was last modified "+lastModDate+".</h6>"
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
</head>
<body onLoad="scrollingMsg(); popUpNotice(); copyRight();">
<div class="center-div">
<p class="center-items"><img src="chapter10-1banner.jpg" alt="banner" /></p>
</div>
<div class="center-div">
<form id="msgForm">
<p style="text-align:center">
<input type="text" name="scrollingMsg" size="25" /></p>
</div>
<p style="text-align:center; font-size:16; font-weight:bold;">Home Mortgage Loan Payment Calculator</p>
<p class="block"><strong>Directions: </strong>Enter the agreed selling price, press the tab key, enter the down payment and press the tab key. The loan amount will be calculated automatically. Then enter the interest rate and the number of years for the loan and click the Calculate button.</p>
<div class="center-div">
<form id="homeLoanForm" method="post">
<table>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Sales Price:
</td>
<td class="align-left"><input type="text" name="SaleAmount" size="9" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Down Payment in Dollars
</td>
<td class="align-left"><input name="DownPayment" type="text" id="DownPayment" size="9" onBlur="validSalesAmt()" /></td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Loan Amount
</td>
<td class="align-left"><input name="LoanAmount" type="text" id="LoanAmount" size="9" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Interest Rate (e.g. 5.9):
</td>
<td class="align-left"><input name="Rate" type="text" id="Rate" size="5" maxlength="5" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Number of Years:
</td>
<td><select name="Years" id="Years">
<option value="0">Select Number of Years</option>
<option value=10>10</option>
<option value=15>15</option>
<option value=20>20</option>
<option value=30>30</option>
</select></td>
</tr>
<tr>
<td class="right-align">
<input name="button" type="button" value="Calculate" onClick="CalcLoanAmt()"/>
</td>
<td class="align-left">
<input name="Reset" type="reset" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">Monthly Payment:</span>
</td>
<td><input type="text" name="Payment" id="Payment" value=" " size="12" /></td>
</tr>
<tr>
<td colspan="2" class="align-center">
<span style="color:#cc0000; font-size:12px;">* Indicates a required field.</span>
</td>
</tr>
</table>
</form>
</div>
<div id="displayDateLast">
</div>
</body>
</html>
when the browser finds a syntax-error in a <script> he will discard the entire script-code within this script.
a simple demonstration:
<body onLoad="foo();bar();foobar();">
<script type="text/javascript">
var a + b;//syntax-error, similar to line 86 in your script
//this will not run because this script has been discarded
//because of the syntax-error above
function bar(){
alert('bar works');
}
</script>
<script type="text/javascript">
//this will run because here is no syntax-error,
//the function is available
function foo(){
alert('foo works');
}
//although this function is available too this will not run
//because of the error forced by the call of bar()
function foobar(){
alert('foobar works');
}
</script>
</body>
That's why the function scrollingMsg will be unknown, although there is no syntax-error within this function, because there are multiple syntax-errors in this script, fix them.

how to show an alert after validation but before submission

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>

Categories

Resources