Using radio buttons within javascript for a calculation - javascript

I've been working at this for a few hours and I cannot, for the life of my figure out how to do this.
So, I wanted to make a calculation in java-script (on the back of HTML). And I was wondering how I could get the radio button to chance the value of a number of vars. E.G (female radio button checked, var a = 10, var x = 20, etc..., but if male radio button checked, var a = 34,var x = 32, etc...)
also along with this I wanted to know if i could do a long sum like for example (bmr = a + (x * weight) + (y * height) - (z * age)). Then finally diplay all this information on a different text field.
HTML
<!DOCTYPE html PUBLIC>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<SCRIPT type="text/javascript" src="jstest.js">
</SCRIPT>
</head>
<body>
<form action="" method="post" name="caloriecalc">
<table>
<tr>
<td>Age:</td>
<td>
<input type="text" name="age" size="5" />
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<label>
<input type="radio" name="gender" value="male" />Male</label>
<br />
<label>
<input type="radio" name="gender" value="female" />Female</label>
<br />
</td>
</tr>
<tr>
<td>Weight:</td>
<td>
<input type="text" name="weight" size="7" />KG</td>
</tr>
<tr>
<td>Height:</td>
<td>
<input type="text" name="height" size="7" />CM</td>
</tr>
<tr>
<td>
<label>Exercise Level:</label>
</td>
<td>
<select name="activity">
<option value="1.2">Sedentary (little or no exercise)</option>
<option value="1.375">Lightly active (exercise/sports 1-3 days/wk</option>
<option value="1.55">Mod. active (exercise/sports 3-5 days/wk)</option>
<option value="1.725">Very active (exercise/sports 6-7 days/wk)</option>
<option value="1.9">Extr. Active (daily exercise/sports & physical job))</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input name="calc" type="button" value="Calculate" onclick="validate()" />
</td>
</tr>
<tr>
</table>
</form>
<table width="100%">
<tr>
<td width="50%" align="right">BMR</td>
<td width="50%" id="bmr"></td>
</tr>
</table>
</body>
</html>
JAVASCRIPT
function validate() {
var age = document.caloriecalc.age.value;
var weight = document.caloriecalc.weight.value;
var height = document.caloriecalc.height.value;
if (age <= 0 || parseInt(age) != age) {
alert("Please enter a valid age.");
} else if (weight <= 0 || isNaN(Number(weight))) {
alert("Please enter a valid weight.");
} else if (height <= 0 || isNaN(Number(height))) {
alert("Please enter a valid height.");
} else { //all the data has been validated
calculate(parseInt(age), parseFloat(weight), parseFloat(height));
}
}
function calculate(age, weight, height) {
}

Try something like
function validate() {
var i , gender;
var age = document.caloriecalc.age.value;
var weight = document.caloriecalc.weight.value;
var height = document.caloriecalc.height.value;
for(i = 0; i < document.caloriecalc.gender.length; i++){
if(document.caloriecalc.gender[i].checked){
gender = document.caloriecalc.gender[i].value;
}
}
if (age <= 0 || parseInt(age) != age) {
alert("Please enter a valid age.");
} else if (!gender) {
alert("Please enter a valid gender.");
} else if (weight <= 0 || isNaN(Number(weight))) {
alert("Please enter a valid weight.");
} else if (height <= 0 || isNaN(Number(height))) {
alert("Please enter a valid height.");
} else { //all the data has been validated
calculate(parseInt(age), parseFloat(weight), parseFloat(height), gender);
}
}
function calculate(age, weight, height, gender) {
var a, x, y = 1, z = 1;
switch(gender){
case "male":
a= 34;
x =32;
break;
case "female":
a= 10;
x =20;
break;
}
var bmr = a + (x * weight) + (y * height) - (z * age);
document.getElementById('bmr').innerHTML = bmr;
}
Demo: Fiddle
Note: I don't know the value for y and z as you haven't mentioned them

You can get the value of radio button by using :-
var lengthh=document.caloriecalc.gender.length;
for(var i=0;i<lengthh;i++){
if(document.caloriecalc.gender[i].checked){
gender = document.caloriecalc.gender[i].value;
}
}
Now pass the values to calculate function and do you calculation as below :-
function calculate(age, weight, height, gender) {
var a=0, x=0, y = 1, z = 1;
if(gender=='male'){
a= 34;
x =32;
}else{
a= 10;
x =20;
}
//Now the result is
var resultt = a + (x * weight) + (y * height) - (z * age);
document.getElementById('bmr').innerHTML = resultt;
}
Hope it will help you.

Related

I am having trouble getting a select tag to print one of the two options to a table and then calculate if one of them is selected to add to a total

The program I am trying to write is a pizza ordering program and the majority of it already works, but for my two selection options I want to have the value of one of the options print to the screen and then if the delivery option is selected to add 2 to the total.
Here is what I am using currently for the selection.
function getPizza(){
var price = 0;
var size = "";
var top = 0;
var total = 0;
var select_price = 0;
var select_option = "";
var s1 = document.getElementById("s1");
var s2 = document.getElementById("s2");
var s3 = document.getElementById("s3");
var s4 = document.getElementById("s4");
if(s1.checked==true)
{
price = 8.00;
size = "Small";
}
else if(s2.checked==true)
{
price = 10.00;
size = "Medium";
}
else if(s3.checked==true)
{
price = 12.00;
size = "Large";
}
else if(s4.checked==true)
{
price = 14.00;
size = "X-Large";
}
else
alert("No size selected");
document.getElementById("p_result").innerHTML = "$" + price;
document.getElementById("s_result").innerHTML = size;
var t1 = document.forms["order"]["topping1"].checked;
var t2 = document.forms["order"]["topping2"].checked;
var t3 = document.forms["order"]["topping3"].checked;
var t4 = document.forms["order"]["topping4"].checked;
var t5 = document.forms["order"]["topping5"].checked;
document.getElementById("t_options").innerHTML = '';
if(t1 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Pepperoni" + "</br>";
}
if(t2 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Sausage" + "</br>";
}
if(t3 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Bacon" + "</br>";
}
if(t4 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Onions" + "</br>";
}
if(t5 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Spinach" + "</br>";
}
document.getElementById("t_result").innerHTML = "$ " + top;
//if structure I thought would work for adding to total.
if (select_option == true)
select_price = select_price + 2;
document.getElementById("sel_opt").innerHTML = select_option;
document.getElementById("sel_price").innerHTML = select_price;
total = total + price + top + select_price;
document.getElementById("total_result").innerHTML = "Your Current Total is $ " + total;
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<h1>Pizza Program </h1>
<form id="order" name="order">
<label for="first_last"> Name:</label>
<input type="text" name="first_last" id="first_last" placeholder="First Last"> <br>
<p> Please choose your size of pizza:</p>
<input type="radio" name="size" id="s1" value="Small"> Small - $8</input><br>
<input type="radio" name="size" id="s2" value="Medium"> Medium - $10</input><br>
<input type="radio" name="size" id="s3" value="Large"> Large - $12</input><br>
<input type="radio" name="size" id="s4" value="X-Large"> Extra Large - $14</input><br>
<p>Please choose your topping ($1.50 each): </p>
<input type="checkbox" name="topping1" id="topping1" value="pepperoni"> Pepperoni </input><br>
<input type="checkbox" name="topping2" id="topping2" value="sausage"> Sausage </input><br>
<input type="checkbox" name="topping3" id="topping3" value="bacon"> Bacon </input><br>
<input type="checkbox" name="topping4" id="topping4" value="onions"> Onions </input><br>
<input type="checkbox" name="topping5" id="topping5" value="spinach"> Spinach </input><br> <br>
<select name="pick_deliv" id="select1">
<option id="pick_up" value="Pickup">Pick up</option>
<option id="deliv" value="Delivery">Delivery</option>
</select> <br> <br>
</form>
<button onclick="getPizza()" id="btn1"> Confirm Order</button>
<h1 id="name_result"> Your Order </h1> <br> <br>
<table style="width:50%">
<tr>
<th>Description</th>
<th>Option</th>
<th>Price</th>
</tr>
<tr>
<td> Size </td>
<td id="s_result"> </td>
<td id="p_result"> </td>
</tr>
<tr>
<td> Toppings </td>
<td id="t_options"> </td>
<td id="t_result"> </td>
</tr>
<tr>
<td> Pick-Up/Delivery</td>
<td id="sel_opt"> </td>
<td id="sel_price"> </td>
</tr>
</table>
<h4 id="total_result">Your Current Total is $ </h4>
<p id="demo"> </p>
</body>
</html>

Javascript form calculation errors

Im getting uncaught type error for estimateCost, also im having issues with how to double the price with spouse. I'm suppose to have an alert window that displays the estimate cost based on selections made from city, number of days, and other options. TY!
<html>
<head>
<script language="JavaScript">
var city_prices = new Array();
city_prices["New York City"] = 0;
city_prices["Boston"] = 0;
city_prices["San Francisco"] = 200;
city_prices["Los Angeles"] = 200;
// getCityPrice() finds the price based on the city .
// Here, we need to take user's the selection from radio button selection
function getCityPrice() {
var cityPrice = 0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["form1"];
//Get a reference to the cake the user Chooses name=radCity":
var selectedCity = theForm.elements["radCity"];
//Here since there are 4 radio buttons selectedCity.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCity.length; i++) {
//if the radio button is checked
if (selectedCity[i].checked) {
//we set cityPrice to the value of the selected radio button
//i.e. if the user choose NYC we set to 0
//by using the city_prices array
//We get the selected Items value
//For example city_prices["New York City".value]"
cityPrice = city_prices[selectedCity[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cityPrice
return cityPrice;
}
var number_days = new Array();
number_days["3"] = 450;
number_days["4"] = 600;
number_days["5"] = 750;
number_days["6"] = 900;
number_days["7"] = 1050;
number_days["8"] = 1350;
number_days["9"] = 1500;
number_days["10"] = 1650;
number_days["11"] = 1800;
number_days["12"] = 1950;
number_days["13"] = 2100;
number_days["14"] = 2250;
number_days["15"] = 2400;
//This function finds the day price based on the
//drop down selection
function getDayPrice() {
var dayPrice = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the select id="selNumberDays"
var selectedDays = theForm.elements["selNumberDays"];
//set dayPrice equal to value user chose
//For example number_days["3".value] would be equal to 450
dayPrice = number_days[selectedDays.value];
//finally we return dayPrice
return dayPrice;
}
//chksFirst() finds the candles price based on a check box selection
function chksFirst() {
var chkFirst = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkFirst"
var includeFirst = theForm.elements["chkFirst"];
//If they checked the box set first class to 500
if (includeFirst.checked == true) {
chkFirst = 500;
}
//finally we return the firstClass
return chkFirst;
}
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse() {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalPrice = getCityPrice() + getDayPrice() +
chksFirst() + chksSpouse();
alert(totalPrice);
}
</script>
</head>
<body>
<table align="left" width="600px" border="0" cellpadding="5px">
<tr>
<td>
<form name="form1" id="form1">
<table border="0">
<tr>
<td width="300px"><strong>Last Name: </strong>
</td>
<td width="300px">
<input type="text" name="txtFirstName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>First Name: </strong>
</td>
<td>
<input type="text" name="txtLastName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>Nationality: </strong>
</td>
<td>
<select name="selNationality">
<option value="amer">USA</option>
<option value="can">Canada</option>
<option value="mex">Mexico</option>
<option value="ger">Germany</option>
<option value="fra">France</option>
</select>
</td>
</tr>
<tr>
<td><strong>City you wish to visit: </strong>
</td>
<td>
<input type="radio" name="radCity" value="New York City" />New York City
<br />
<input type="radio" name="radCity" value="Boston" />Boston
<br />
<input type="radio" name="radCity" value="San Francisco" />San Francisco ($200 surcharge)
<br />
<input type="radio" name="radCity" value="Los Angeles" />Los Angeles ($200 surcharge)
<br/>
</td>
</tr>
<tr>
<td><strong>Number of days ($150 per day): </strong>
</td>
<td>
<select name="selNumberDays" id="selNumberDays">
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</td>
</tr>
<tr>
<td><strong>Other options: </strong>
</td>
<td>
<input type="checkbox" name="chkFirst" id="chkFirst" />First Class Only ($500 surcharge)
<br />
<input type="checkbox" name="chkSpouse" id="chkSpouse" />Traveling with Spouse (All costs doubled)
<br />
</td>
</tr>
<tr>
<td align="right">
<input type="button" value="Give me an estimate!" onClick="estimateCost()" id="estimateCost" />
</td>
<td align="left">
<input type="reset" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
On the button input with the onClick="estimateCost()" code, remove the id="estimateCost". It's causing the error for some reason. You should really be using an onClick listener though instead of an inline onclick:
Inline onclick JavaScript variable
For the total with spouse, you might want to rework it to something like this where you pass the pre-spouse price into the chksSpouse function and use it's return as the total price.
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse(totalPrice) {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var preSpouseTotal = getCityPrice() + getDayPrice() + chksFirst();
var totalPrice = chksSpouse(preSpouseTotal);
alert(totalPrice);
}

Paypal button and checkout with jquery

I have this code:
<script>
/* Set rates + misc */
var taxRate = 0.08;
var shippingRate = 0.00;
var fadeTime = 300;
/* Assign actions */
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
/* Recalculate cart */
function recalculateCart()
{
var subtotal = 0;
/* Sum up row totals */
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
/* Calculate totals */
var tax = subtotal * taxRate;
var shipping = (subtotal > 0 ? shippingRate : 0);
var total = subtotal + tax + shipping;
/* Update totals display */
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-shipping').html(shipping.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
/* Update quantity */
function updateQuantity(quantityInput)
{
/* Calculate line price */
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
/* Update line price display and recalc cart totals */
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
/* Remove item from cart */
function removeItem(removeButton)
{
/* Remove row from DOM and recalc cart total */
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
//# sourceURL=pen.js
</script>
The full demo can watch here:
http://codepen.io/justinklemm/pen/zAdoJ
¿As I can pay by paypal with jquery checkout button?
Example.
Pay Total: $ 90.57 with Paypal
My code button paypal:
<input class="checkout" type="image" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" border="0" name="submit" style="vertical-align:middle" alt="PayPal">
Thanks.
maybe this can help, try playing around with it.
<SCRIPT TYPE="text/javascript">
function MM_goToURL() { //v3.0
var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function Dollar (val) { // force to valid dollar amount
var str,pos,rnd=0;
if (val < .995) rnd = 1; // for old Netscape browsers
str = escape (val*1.0 + 0.005001 + rnd); // float, round, escape
pos = str.indexOf (".");
if (pos > 0) str = str.substring (rnd, pos + 3);
return str;
}
function ReadForm (obj1) { // process un-named selects
var i,j,amt,des,obj,pos,tok,val;
var ary = new Array ();
amt = obj1.baseamt.value*1.0; // base amount
des = obj1.basedes.value; // base description
for (i=0; i<obj1.length; i++) { // run entire form
obj = obj1.elements[i]; // a form element
if (obj.type == "select-one" && // just get selects
obj.name == "") { // must be un-named
pos = obj.selectedIndex; // which option selected
val = obj.options[pos].value; // selected value
ary = val.split (" "); // break apart
for (j=0; j<ary.length; j++) { // look at all items
// first we do single character tokens...
if (ary[j].length < 2) continue;
tok = ary[j].substring (0,1); // first character
val = ary[j].substring (1); // get data
if (tok == "#") amt = val * 1.0;
if (tok == "+") amt = amt + val*1.0;
if (tok == "%") amt = amt + (amt * val/100.0);
if (tok == "#") { // record item number
if (obj1.item_number) obj1.item_number.value = val;
ary[j] = ""; // zap this array element
}
// Now we do 3-character tokens...
if (ary[j].length < 4) continue;
tok = ary[j].substring (0,3); // first 3 chars
val = ary[j].substring (3); // get data
if (tok == "s1=") { // value for shipping
if (obj1.shipping) obj1.shipping.value = val;
ary[j] = ""; // clear it out
}
if (tok == "s2=") { // value for shipping2
if (obj1.shipping2) obj1.shipping2.value = val;
ary[j] = ""; // clear it out
}
}
val = ary.join (" "); // rebuild val with what's left
if (des.length == 0) des = val; // 1st storage?
else des = des + ", " + val; // nope, accumulate value
}
}
obj1.item_name.value = des;
obj1.amount.value = Dollar (amt);
if (obj1.tot) obj1.tot.value = "$" + Dollar (amt);
}
</SCRIPT>
<FORM id=viewcart name=viewcart action=https://www.paypal.com/cgi-bin/webscr
method=post>
</FORM>
<FORM onSubmit="this.target = 'paypal';
ReadForm (this.form);"
action=https://www.paypal.com/cgi-bin/webscr method=post>
<P>
<INPUT type=hidden value=_cart name=cmd>
<INPUT type=hidden value=1 name=add>
<INPUT type=hidden value=my#email.com name=business>
<INPUT type=hidden name=item_name>
<INPUT type=hidden name=item_number>
<INPUT type=hidden name=amount>
<INPUT type=hidden value=USD name=currency_code>
<INPUT type=hidden value=USD name=lc>
<INPUT type=hidden value=00 name=shipping>
<INPUT type=hidden value=00.00 name=baseamt>
<INPUT type=hidden VALUE="itemname" name=basedes>
<INPUT TYPE="hidden" NAME="on0" VALUE="Details">
<INPUT TYPE="hidden" NAME="os0" VALUE="moredetails" MAXLENGTH="800">
<BR>
<BR>
</P>
<TABLE WIDTH="400px" BORDER="0" CELLPADDING="0" CELLSPACING="0" align="right">
<TR>
<TD ALIGN="left">
<p class="heading"> </p>
<p class="main"> dropdown1</p>
<p class="heading"> </p>
</TD>
<TD>
<SELECT STYLE="WIDTH: 240px" onChange="ReadForm (this.form);">
<OPTION selected>Please select </OPTION>
<OPTION VALUE="option1 +125.00">option1</OPTION>
<OPTION VALUE="option2 +90.00">option2</OPTION>
<OPTION VALUE="option3 +40.00">option3</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD ALIGN="left">
<p class="heading"> </p>
<p class="main"> dropdown2</p>
<p class="heading"> </p>
</TD>
<TD>
<SELECT STYLE="WIDTH: 240px" onChange="ReadForm (this.form);">
<OPTION selected>Please select </OPTION>
<OPTION VALUE="option1 +55.00">option1</OPTION>
<OPTION VALUE="option2 +99.00">option2</OPTION>
<OPTION VALUE="option3 +44.00">option3</OPTION>
</SELECT>
</TD>
</TR>
<tr>
<TR>
<TD ALIGN="left">
<p class="main"> </p>
<p class="main"> Price</p>
<p class="main"> </p>
</TD>
<TD ALIGN="left">
<INPUT class=nbor size=8 value=00.00 name=tot>
</TD>
</TR>
<TD align="left">
<label for="submit"></label>
<TD align="left">
<input type="image" src="/addtocart2.png" name="submit" id="submit" value="submit" >
</div>
</div></td>
</tr>
</table>
</table>
</form>
</TABLE>
</FORM>
</div>

Javascript not working to validate or give total on a sample order form

Ok I created a javascript for a simple HTML form to validate as well as give you a popup of the total or if anything is wrong with one of the inputs.
heres the javascript
function processOrderform() {
var OrderFormObj = document.getElementById("OrderForm");
if (validateInput(OrderFormObj)) {
var total = calculateTotal(OrderFormObj);
alert("Your Total Is: $" + total + ". Thank you for your order! We hope to see you again!");
}
}
function validateInput(OrderFormObj) {
var product1_prices = OrderFormObj.product1.options[OrderFormObj.product1.selectedIndex].value;
var product2_prices = OrderFormObj.product2.options[OrderFormObj.product2.selectedIndex].value;
var product3_prices = OrderFormObj.product3.options[OrderFormObj.product3.selectedIndex].value;
var product4_prices = OrderFormObj.product4.options[OrderFormObj.product4.selectedIndex].value;
var quantity1 = OrderFormObj.quantity1.value;
var quantity2 = OrderFormObj.quantity2.value;
var quantity3 = OrderFormObj.quantity3.value;
var quantity4 = OrderFormObj.quantity4.value;
var taxexempt = OrderFormObj.taxexempt.value;
var quantity1OK, quantity2OK, quantity3OK, quantity4OK, taxexemptOK;
quantity1OK = validateQuantity1(quantity1);
quantity2OK = validateQuantity2(quantity2);
quantity3OK = validateQuantity3(quantity3);
quantity4OK = validateQuantity4(quantity4);
taxexemptOK = validateTaxExempt;
if (OrderFormObj.tax.checked) {
taxexemptOK = validateTaxExempt(taxexempt);
}
return quantity1OK && quantity2OK && emailOK && taxexemptOK;
}
function validateQuantity1(quantity1) {
if (isNaN(quantity1)) {
alert("Error: Please input a number for processor quantity.")
return false;
}
if (quantity1 < 0 || quantity1 > 50) {
alert("Error: The maximum quantity of processors you can order is 50. Please select a smaller amount or contact us for more information.")
return false;
}
return true;
}
function validateQuantity2(quantity2) {
if (isNaN(quantity2)) {
alert("Error: Please input a number for storage drive quantity.")
return false;
}
if (quantity2 < 0 || quantity2 > 50) {
alert("Error: The maximum quantity of storage drives you can order is 50. Please select a smaller amount or contact us for more information.")
return false;
}
return true;
}
function validateQuantity3(quantity3) {
if (isNaN(quantity3)) {
alert("Error: Please input a number for memory quantity.")
return false;
}
if (quantity3 < 0 || quantity3 > 50) {
alert("Error: The maximum quantity of memory you can order is 50. Please select a smaller amount or contact us for more information.")
return false;
}
return true;
}
function validateQuantity4(quantity4) {
if (isNaN(quantity4)) {
alert("Error: Please input a number for graphics card quantity.")
return false;
}
if (quantity4 < 0 || quantity4 > 50) {
alert("Error: The maximum quantity of graphics cards you can order is 50. Please select a smaller amount or contact us for more information.")
return false;
}
return true;
}
function validateTaxExempt(taxexempt) {
var p = taxexempt.search(/^\d{8}$/);
if (p == 0)
return true;
else {
alert("Error: Invalid tax-exempt code. Please enter an 8-digit code.");
return false;
}
}
function calculateTotal(OrderFormObj) {
var product1_prices = OrderFormObj.product1.options[OrderFormObj.product1.selectedIndex].value;
alert("Processor Price is $" + product1_prices);
var quantity1 = OrderFormObj.quantity1.value;
alert("Your processor quantity is " + quantity1);
var product2_prices = OrderFormObj.product2.options[OrderFormObj.product2.selectedIndex].value;
alert("Storage Drive Price is $" + product2_prices);
var quantity2 = OrderFormObj.quantity2.value;
alert("Your storage drive quantity is " + quantity2);
var product3_prices = OrderFormObj.product3.options[OrderFormObj.product3.selectedIndex].value;
alert("Memory price is $" + product3_prices);
var quantity3 = OrderFormObj.quantity3.value;
alert("Your memory quantity is " + quantity3);
var product4_prices = OrderFormObj.product4.options[OrderFormObj.product4.selectedIndex].value;
alert("Graphics Card price is $" + product4_prices);
var quantity4 = OrderFormObj.quantity4.value;
alert("Your graphics card quantity is " + quantity4);
var taxexempt = OrderFormObj.taxexempt.value;
alert("Your tax exempt code is " + taxexempt);
var quantity1OK, quantity2OK, quantity3OK, quantity4OK, taxexemptOK;
var checkboxs = OrderFormObj.service;
for (var i = 0; i < checkbox.length; i++) {
if (checkboxs[i].checked) {
var services_prices = checkbox[i].value;
break;
}
}
var getProduct1Price = parseFloat(product1_prices) * parseFloat(quantity1);
var getProduct2Price = parseFloat(product2_prices) * parseFloat(quantity2);
var getProduct3Price = parseFloat(product3_prices) * parseFloat(quantity3);
var getProduct4Price = parseFloat(product4_prices) * parseFloat(quantity4);
var service_price = parseFloat(document.getElementById('service').value);
var total = getProduct1Price + getProduct2Price + getProduct3Price + getProduct4Price + service_price;
return total;
}
and heres the html for it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- bmi5.html -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="orderscript.js">
</script>
<title>Products & Services</title>
</head>
<body>
<h1>PC Products</h1>
<form id="OrderForm" method="post" action=""
onsubmit="processOrderform()">
<tr>
<td><label for="product1">Processors:</label></td>
<td><select id="product1" name="product1">
<option>Select Device</option>
<option value="139.99">Intel i3 - $140</option>
<option value="189.99">Intel i5 - $190</option>
<option value="239.99">Intel i7 - $240</option>
</select></td>
<td><label for="quantity1">Quantity :</label></td>
<td><input id="quantity1" type="text" name="quantity1" size ="1" /></td>
</tr><br />
<tr>
<td><label for="product2">Storage:</label></td>
<td><select id="product2" name="product2"></td>
<td><option>Select Device</option>
<option value="149.99">SSD 128GB - $149.99</option>
<option value="249.99">SSD 256GB - $249.99</option>
<option value="519.00">SSD 512GB - $519.00</option>
<option value="69.99">HDD 500GB - $69.99</option>
<option value="109.99">HDD 1TB - $109.99</option>
<option value="149.99">HDD 1.5TB - $149.99</option>
<option value="199.99">HDD 3TB - $199.99</option>
</select></td>
<td><label for="quantity2">Quantity :</label></td>
<td><input id="quantity2" type="text" name="quantity2" size ="1"></td>
</tr><br />
<tr>
<td><label for="product3">Memory:</label></td>
<td><select id="product3" name="product3"></td>
<td><option>Select Device</option>
<option value="59.99">DDR3 8GB - $59.99</option>
<option value="109.99">DDR3 16GB - $109.99</option>
<option value="209.99">DDR3 32GB - $209.99</option>
</select></td>
<td><label for="quantity3">Quantity :</label></td>
<td><input id="quantity3" type="text" name="quantity3" size ="1"></td>
</tr><br />
<tr>
<td><label for="product4">Graphics Card:</label></td>
<td><select id="product4" name="product4"></td>
<td><option>Select Device</option>
<option value="139.99">Nvidia - $649.99</option>
<option value="189.99">AMD - $449.99</option>
</select></td>
<td><label for="quantity4">Quantity :</label></td>
<td><input id="quantity4" type="text" name="quantity4" size ="1"></td>
</tr><br />
<br />
<table> Service and Repair
<tr><td><input id="virus" type="checkbox" name="service" value="99.99"></td>
<td>Virus Removal</td> <td align="right"><tt>99.99</tt></td></tr>
<tr><td><input id="lesson" type="checkbox" name="service" value="29.99"></td>
<td>1 Hour Computer Lessons</td> <td align="right"><tt>29.99</tt></td></tr>
<tr><td><input id="assembly" type="checkbox" name="service" value=49.99"></td>
<td>PC Assembly</td> <td align="right"><tt>49.99</tt></td></tr>
</table>
<br />
<h4><i>*Sales Tax of 8.25% applies</i></h4>
<td>Tax exempt check box:
<input type="checkbox" name="reply" value="yes" /><br /></td>
<p>
<input type="hidden" id="itemname" name = "itemname" value= "">
<td><input type="submit" value="Submit your order" /></td>
<td><input type="reset" value="Reset form" /></td>
</p>
</form>
</body>
</html>
any input would be great.
If you are accessing some form element with its 'id' then it is not required to use form id also with them. You can simply access the form elements like this:
var product1 = document.getElementById('product1').value;
If you want to access the form elements with their names then you have to use form name too. Assuming your form name is 'OrderForm', It will be like this:
document.forms['OrderForm']['product1'].value;
These things you have to correct in your javascript part. Secondly, you have used some codes like:
var quantity1 = OrderFormObj.quantity1.value;
This also needs to be corrected. If you want quantity1 field value, you can simply get it like this:
var quantity1 = document.getElementById('quantity1').value;

Alert box shows up multiple times on javascript

This is very simple code, and similar to my other question.
When I click submit, the alert box shows up three times for option one, twice for two, and once for three.
Here is the part of the code where the problem is most probably located:
var chosen = ""
var len = document.ExamEntry.r1.length
for (var i = 0; i < len; i++) {
if (document.ExamEntry.r1[i].checked) {
chosen = document.ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
And here is my whole code. It all works fine except for this.
<!-- saved from url=(0055)file:///C:/Users/Bartek/Downloads/Exam%20entry4.1.2.htm -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></head><body><h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="file:///C:/Users/Bartek/Downloads/success.html">
<input type="radio" name="r1" value="GCSE">GCSE
<input type="radio" name="r1" value="AS">AS
<input type="radio" name="r1" value="A2">A2
<table width="50%" border="0">
<tbody>
<tr>
<td id="name" style="color: black; ">Name</td>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td id="subject" style="color: black; ">Subject</td>
<td>
<input type="text" name="subject">
</td>
</tr>
<tr>
<td id="enumber" style="color: black; ">Examination Number</td>
<td>
<input type="text" name="enumber">
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Submit" onclick=" return validateForm();">
</td>
<td>
<input type="reset" name="Reset" value="Reset">
</td>
</tr>
</tbody></table>
</form>
<script>
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.enumber.value.length != 4) {
msg += "The examination number must be exactly four characters long \n";
document.ExamEntry.enumber.focus();
document.getElementById('enumber').style.color = "red";
result = false;
}
var chosen = ""
var len = document.ExamEntry.r1.length
for (var i = 0; i < len; i++) {
if (document.ExamEntry.r1[i].checked) {
chosen = document.ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
if (msg == "") {
return result;
} {
alert(msg);
return result;
}
}
</script>
</body>
</html>
This is GCSE computing coursework.
for (var i = 0; i <len; i++) {
if (document. ExamEntry.r1[i].checked) {
chosen = document. ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
chosen won't be "" if it was set before; you don't set it back to "" if the item wasn't checked, and so it'll confirm the last one that was. Just merge them.
for(var i = 0; i < document.ExamEntry.r1.length; i++) {
if(document.ExamEntry.r1[i].checked) {
confirm(document.ExamEntry.r1[i].value);
}
}
You were missing an else.
if (!msg) {
return result;
} else {
alert(msg);
return result;
}

Categories