checkbox - check at least one box has been selected - javascript

To validate a statement I have made sure that the checkboxes and quantities are consistent with each other but I haven't made sure that at least one product has been selected or a total quantity greater than zero is supplied. How would I do this?
if (((document.form1.summer.checked) && (summer2012 <= 0)) ||
((document.form1.autumn.checked) && (autumn2012 <= 0)) ||
((document.form1.winter.checked) && (winter2012 <= 0)))
{
alertmsg = alertmsg + "Please enter Quantity" + "\n";
}
else if (((!document.form1.summer.checked) && (summer2012 > 0)) ||
((!document.form1.autumn.checked) && (autumn2012 > 0)) ||
((!document.form1.winter.checked) && (winter2012 > 0)))
{
alertmsg = alertmsg + "Please choose Product" + "\n";
}
HTML:
<tr>
<td align="right">Summer 2012</td>
<td>
<input type="checkbox" name="summer" value="Summer 2012" />
</td>
<td align="center" width="69">
<div align="right">20.00</div>
</td>
<td width="216">
<input name="summer2012" type="text" size="5" value="0" />
</td>
</tr>
<tr>
<td align="right">Autumn 2012</td>
<td>
<input type="checkbox" name="autumn" value="Autumn 2012" />
</td>
<td align="center" width="69">
<div align="right">20.00</div>
</td>
<td>
<input name="autumn2012" type="text" size="5" value="0" />
</td>
</tr>
<tr>
<td align="right">Winter 2012</td>
<td>
<input type="checkbox" name="winter" value="Winter 2012" />
</td>
<td align="center" width="69">
<div align="right">20.00</div>
</td>
<td>
<input name="winter2012" type="text" size="5" value="0" />
</td>
</tr>

You appear to already have a test to confirm that for any checked box there must be a corresponding (positive) amount, and a second test to confirm that any positive amount also has a check against it.
All you therefore need to do is check that some checkbox is checked.
var f = document.form1;
if (f.summer.checked || f.autumn.checked || f.winter.checked) {
// we're OK!
}

This is how I would check if any checkbox has been checked:
var checkboxElements = [
document.form1.ch1,
document.form1.autumn,
document.form1.winter,
document.form1.summer
];
function anyChecked(checkboxElements) {
for(var i = 0; i < checkboxElements.length; i++)
if(checkboxElements[i].checked)
return true;
return false;
}

Related

How i want to write function when i click on button calculate order, it will show the ouput

The cleaning total I got is from total laundry.
I have written the function for calculate tax amount and total order amount. but I'm not sure which line got error. It's more confusing when I only can use one button (calculate order) for 2 function.
function calculateTaxAmount() {
let cleaningTotal = document.getElementById("cleaningTotal");
let tax = 5.75;
let taxAmount = cleaningTotal * tax / 100;
document.getElementById("taxAmount").value = taxAmount;
}
function processOrder() {
var f1 = document.getElementById('sum').value;
var f2 = document.getElementById('sumpants').value;
var f3 = document.getElementById('sumItem1').value;
var f4 = document.getElementById('sumItem2').value;
var f5 = document.getElementById('sumItem3').value;
var f6 = document.getElementById('sumItem4').value;
if (f1 == "") f1 = 0;
if (f2 == "") f2 = 0;
if (f3 == "") f3 = 0;
if (f4 == "") f4 = 0;
if (f5 == "") f5 = 0;
if (f6 == "") f6 = 0;
var result = parseInt(f1) + parseInt(f2) + parseInt(f3) + parseInt(f4) + parseInt(f5) + parseInt(f6);
if (!isNaN(result)) {
document.getElementById('cleaningTotal').value = result;
}
var orderTotal = cleaningTotal + tax; {
document.getElementById('orderTotal').value = result
}
}
<input type="button" value="Calculate Order" onclick="processOrder()"><br><br>
<label>Cleaning Total</label>
</td>
<td>
<div>
<input type="text" name="cleaningTotal" id="cleaningTotal" value="">
</div>
</td>
<td> </td>
</tr>
<tr class="tbl-foot">
<td colspan="3">
<label>Tax Rate</label>
</td>
<td>
<input type="text" name="taxRate" id="taxRate" value="5.75">%
</td>
<td> </td>
</tr>
<tr class="tbl-foot">
<td colspan="3">
<label>Tax Amount : </label>
</td>
<td>
<div>
<input type="text" name="taxAmount" id="taxAmount" onclick="processOrder()" value="">
</div>
</td>
<td> </td>
</tr>
<tr class="tbl-foot">
<td colspan="3">
<label>Order Total : </label>
</td>
<td>
<div>
<input type="text" name="orderTotal" id="orderTotal" value="">
</div>
</td>
<td> </td>
</tr>

HTML table <td> linked to Javascript how?

I have an order form within an HTML table associated to some JavaScript verification logic. The current code works but I would like some enhancements to be implemented.
Currently, pressing the "verify" order button gives me the following output:
Line 0 = 1 Qty Line 1 = 4 Qty Line 2 = 2 Qty
Instead of showing table lines numbers followed by quantity value, I need the text to contain the actual products names. E.g. "Line 0 = 1" → "Apple = 1" …
I cannot really seem to figure it out can someone tell me how to do this?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
<!-- Original: Mike McGrath (mike_mcgrath#example.net) -->
<!-- Web Site: http://website.example.net/~mike_mcgrath/ -->
<!--
function count(f, n, u) {
f.line_sum[n].value = f.line[n].value * u;
f.line_sum[n].value = Math.ceil(f.line_sum[n].value * 1000) / 1000;
f.line_sum[n].value = Math.floor(f.line_sum[n].value * 1000) / 1000;
f.line_sum[n].value = Math.round(f.line_sum[n].value * 100) / 100;
if (f.line_sum[n].value == "NaN") {
alert("Error:\nYou may only enter numbers...\nPlease retry");
f.line[n].value = f.line[n].value.substring(0, f.line[n].value.length - 1);
f.line_sum[n].value = f.line[n].value * u;
if (f.line_sum[n].value == "0") f.line_sum[n].value = "";
} else {
var gt = 0;
for (i = 0; i < f.line_sum.length; i++) {
gt += Math.ceil(f.line_sum[i].value * 1000) / 1000;
}
gt = Math.round(gt * 1000) / 1000;
f.grand_total.value = "$ " + gt;
decimal(f);
}
}
function get_data(f) {
var order_data = "This Order is ...\n";
for (i = 0; i < f.line.length; i++) {
if (f.line[i].value == "") f.line[i].value = "0";
order_data += "Line " + i + " = " + f.line[i].value + " Qty\n";
}
if (f.grand_total.value == "") f.grand_total.value = "Nil";
order_data += "Total Order Value = " + f.grand_total.value;
document.g.order.value = order_data;
}
function decimal(f) {
for (i = 0; i < f.line_sum.length; i++) {
var d = f.line_sum[i].value.indexOf(".");
if (d == -1 && f.line[i].value != 0) f.line_sum[i].value += ".00";
if (d == (f.line_sum[i].value.length - 2)) f.line_sum[i].value += "0";
if (f.line_sum[i].value == "00") f.line_sum[i].value = "";
}
d = f.grand_total.value.indexOf(".");
if (d == -1) f.grand_total.value += ".00";
if (d == (f.grand_total.value.length - 2)) f.grand_total.value += "0";
}
function send_data(g) {
get_data(document.f);
if (document.f.grand_total.value == "Nil") {
var conf = confirm("No items are entered - \nDo you want to submit a blank order?");
if (conf) g.submit();
else init();
} else g.submit();
}
function init() {
document.f.reset();
document.f.line[0].select();
document.f.line[0].focus();
document.g.order.value = "";
}
window.onload = init;
// -->
</SCRIPT>
</head>
<body>
<FORM NAME="f">
<TABLE BGCOLOR="mistyrose" BORDER="2" WIDTH="320" CELLPADDING="5" CELLSPACING="0" SUMMARY="">
<TBODY>
<TR>
<TD COLSPAN="4" ALIGN="center">
<B>Order Form</B>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>
<U>Item</U>
</TD>
<TD>
<U>Qty</U>
</TD>
<TD>
<U>Each</U>
</TD>
<TD ALIGN="right">
<U>Total</U>
</TD>
</TR>
<TR>
<TD>Apple</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,0,5.95)">
</TD>
<TD>$ 5.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>Banana</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,1,10.95)">
</TD>
<TD>$ 10.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR>
<TD>Orange</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,2,20.95)">
</TD>
<TD>$ 20.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>
<INPUT TYPE="button" VALUE="Reset" ONCLICK="init()">
</TD>
<TD COLSPAN="2" ALIGN="right">
<U>Grand Total :</U>
</TD>
<TD ALIGN="right">
<INPUT NAME="grand_total" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR>
<TD COLSPAN="4" ALIGN="center">
<INPUT TYPE="button" VALUE="Press to Verify Order" ONCLICK="get_data(this.form)">
</TD>
</TR>
</TBODY>
</TABLE>
</FORM>
<FORM NAME="g" METHOD="post" ENCTYPE="text/plain" ACTION="mailto:user#isp">
<TABLE BGCOLOR="cadetblue" BORDER="4" WIDTH="320" CELLPADDING="5" CELLSPACING="0" SUMMARY="">
<TBODY>
<TR>
<TD ALIGN="center">
<TEXTAREA NAME="order" ROWS="5" COLS="35">
</body>
</html>

Form Validation with password match

I have two forms inside my body:
<body>
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validate();" />
</td>
</tr>
</table>
</form>
</body>
I would like to do the following:
For each form, validate to ensure it's filled in and also for the second form I want to validate that the two password matched. I have the following:
$( document ).ready(function() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
$('#cpass').blur(function(){
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
}
else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validate() {
if (t != null && y != null && k != null && j != null) {
}
if (t == "" || y == "" || k == "" || j == "") {
alert("fill in");
}
}
I preferred not to mix native JavaScript and validated using pure jQuery only. One of the benefits here is that the empty field check would work for any <form> since it's not tied to any particular form, input name or ids.
$( document ).ready(function() {
$( 'form' ).submit(function(event) {
var $form = $( this );
var checkPass = true;
$form.find( 'input' ).each(function( i, e) {
if (e.value.length === 0) {
event.preventDefault();
alert(e.name + " cannot be empty");
return (checkPass = false);
}
});
if( checkPass && $form.is( '[name="register"]' ) ) {
if( $form.find( '#pass').val() !== $form.find( '#cpass' ).val()) {
event.preventDefault();
alert( 'Passwords do not match.' );
}
}
});
});
Working Demo at JsFiddle.net
Basics:
If you want to check if a variable is not null, ideally, you should use !== & not !=.
If you want to check if a variable is "", ideally, you should use === and not ==.
Check out: http://www.w3schools.com/js/js_comparisons.asp
Use JSFiddle.net to give a better working example of your code WHICH can help others see a demo of your actual code.
Your code currently has lot of scope for optimization. Since its just a basic validation you are trying to achieve, why do you need to use jQuery? Why not just use JavaScript basic variable comparisons?
Google before you ask here. If its so straightforward, your question will get downvoted.
Alert is not the best way to notify the user to fill in. For example, your 'Password Matches' or 'Password Doesn't Match' div is a much better way to notify the user. Use Form Events to validate the form as the user is already filling in the details in the form!
Question responsibly by giving your exact problems and not just pasting the code! How would we know where you are facing a problem.
Variables work in Scope. Check the scope of variable before using them in different functions. For example, you define var t, y, k, j in first function and use it in second function - will throw up an error of undefined variable t.
From what information you provided, here's what I could help with:
HTML:
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onclick="javascript:validateSignin()" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validateRegister();" />
</td>
</tr>
</table>
</form>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#cpass').blur(function () {
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
} else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validateRegister() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
if (t !== null && y !== null && k !== null && j !== null) {}
if (t === "" || y === "" || k === "" || j === "") {
alert("fill in");
}
}
function validateSignin() {
var se= document.getElementById("em").value;
var sp= document.getElementById("up").value;
if (se !== null && sp !== null){ }
if (se === "" || sp === "") {
alert("fill in");
}
}
</script>
Hope it helps! :)

javascript form doesn't work

I have tried to create a javascript form and I can't get it to work. The errors coming up are
Postcode should be in letters and numbers:
Address should be alphanumeric:
Please limit each magazine to 500 copies or less
function display() {
var totprice;
var fname, lname, fullname, addr, postocde, email, telephone, lstitem, quantity, gender;
var prditem1, prditem2, prditem3, summer2012, autumn2012, winter2012, totqty;
var orddate;
fname = document.form1.fname.value;
lname = document.form1.lname.value;
//fullname = fname + " " + lname;
gender = document.form1.gender.value;
addr = document.form1.address.value;
postcode = document.form1.address.value;
email = document.form1.email.value;
telephone = document.form1.telephone.value;
prditem1 = document.form1.summer.value;
prditem2 = document.form1.autumn.value;
prditem3 = document.form1.winter.value;
summer2012 = parseInt(document.form1.summer2012.value);
autumn2012 = parseInt(document.form1.autumn2012.value);
winter2012 = parseInt(document.form1.winter2012.value);
totqty = summer2012 + autumn2012 + winter2012;
orddate = new Date();
dispdate = orddate.getMonth() + 1 + "-" + orddate.getDate() + "-" + orddate.getYear();
var alertmsg = '';
var alphabetic = /^[a-zàâçéèêëîïôûùüÿñ-]*$/i
var alphanumeric = /^[a-zA-Z0-9/./,/-/\n]+$/;
var addrtxt = addr.replace(/(\x0a\x0d|\x0d\x0a)/g, "\n");
var chkpostcode = /^((GIR 0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9] [A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) [0-9][ABD-HJLNP-UW-Z]{2}))$/
var chktelephone = /^0\d{9,10}$/
var chkEmail = /^.+#.+..+$/
var chkquantity = /^([1-9]?\d|[1-4]\d{2}|500)$/
if (chkEmail.test(email) == false) {
alertmsg = alertmsg + "Please enter a valid email." + "\n";
}
if ((alphabetic.test(fname) == false) || (alphabetic.test(lname) == false)) {
alertmsg = alertmsg + "Name should be in alphabets:" + "\n";
}
if (chktelephone.test(telephone) == false) {
alertmsg = alertmsg + "Telephone should be in digits:" + "\n";
}
if (chkpostcode.test(postcode) == false) {
alertmsg = alertmsg + "Postcode should be in letters and numbers:" + "\n";
}
if (alphanumeric.test(addrtxt) == false) {
alertmsg = alertmsg + "Address should be alphanumeric:" + "\n";
}
var gender = document.form1.gender[0].checked;
var gender1 = document.form1.gender[1].checked;
if (!gender && !gender1) {
alertmsg = alertmsg + "please select your gender\n"
}
if (((document.form1.summer.checked) && (summer2012 <= 0)) || ((document.form1.autumn.checked) && (autumn2012 <= 0)) || ((document.form1.winter.checked) && (winter2012 <= 0))) {
alertmsg = alertmsg + "Please enter Quantity" + "\n";
} else if (((!document.form1.summer.checked) && (summer2012 > 0)) || ((!document.form1.autumn.checked) && (autumn2012 > 0)) || ((!document.form1.winter.checked) && (winter2012 > 0))) {
alertmsg = alertmsg + "Please choose Product" + "\n";
}
var f = document.form1;
if (!f.summer.checked && !f.autumn.checked && !f.winter.checked) {
alertmsg = alertmsg + "Please choose at least one edition of the magazine" + "\n";
}
if (chkquantity.test(quantity) <= 500) {
alertmsg = alertmsg + "Please limit each magazine to 500 copies or less:" + "\n";
}
if (alertmsg != "") {
alertmsg = "Please enter the following values \n" + alertmsg;
alert(alertmsg);
} else {
fullname = formatName(fname, lname);
totprice = totalprice();
}
//alert("Thanks for submitting the details");
function totalprice() {
var totprice = 0;
var price = new Array();
price[0] = 20.00;
price[1] = 20.00;
price[2] = 20.00;
var quantity = new Array();
quantity[0] = parseInt(document.form1.summer2012.value);
quantity[1] = parseInt(document.form1.autumn2012.value);
quantity[2] = parseInt(document.form1.winter2012.value);
for (i = 0; i < 3; i++) {
totprice = totprice + quantity[i] * price[i];
}
return (totprice);
}
}
Can anyone suggest what I've done wrong? any help would really be appreciated. thanks
here is the html -
<form name="form1" method="post">
<fieldset id="fieldset">
<legend id="legend">Order the latest Saraysounds Magazine</legend>
<table width="500" border=0 align="left" cellpadding="4" cellspacing="4">
<tr>
<td colspan="2"><div align="left">First
Name</div></td>
<td colspan="2"><input type="text" name="fname"/>
</td>
</tr>
<tr>
<td colspan="2"><div align="left">Second
Name</div></td>
<td colspan="2">
<input type="text" name="lname"/>
</td>
</tr>
<tr>
<td colspan="2"><div align="left">Gender</div></td>
<td colspan="2">
<input type="radio" name="gender" value="M"/>
Male
<input type="radio" name="gender" value="F"/>
Female </td>
</tr>
<tr>
<td colspan="2"><div align="left">Address</div></td>
<td colspan="2"><textarea name="address" cols="30" rows=5 col=40 wrap=soft> </textarea>
</td>
</tr>
<tr>
<td colspan="2"><div align="left">Postcode</div></td>
<td colspan="2"> <input type="text" name="postcode"/>
</td>
</tr>
<tr>
<td colspan="2"><div align="left">Email</div></td>
<td colspan="2">
<input type="text" name="email"/>
</td>
</tr>
<tr>
<td colspan="2"><div align="left">Telephone</div></td>
<td colspan="2">
<input type="text" name="telephone"/>
</td>
</tr>
<tr>
<td colspan="4"><center>
<strong>Select
Magazine</strong>
</center></td>
</tr>
<tr>
<td width="123"><center>
<strong>Product Name</strong>
</center></td>
<td width="30" ><center>
<strong></strong>
</center></td>
<td ><center>
<strong>Price</strong>
</center></td>
<td>
<strong>Quantity</strong>
</td>
</tr>
<tr>
<td align="right">Summer 2012
</td>
<td>
<input type="checkbox" name="summer" value="Summer 2012"/>
</td>
<td align="center" width="69"><div align="right">20.00 </div></td>
<td width="216"><input name="summer2012" type="text" size="5" value="0"/></td>
</tr>
<tr>
<td align="right">Autumn 2012
</td>
<td>
<input type="checkbox" name="autumn" value="Autumn 2012"/>
</td>
<td align="center" width="69"><div align="right">20.00 </div></td>
<td><input name="autumn2012" type="text" size="5" value="0"/></td>
</tr>
<tr>
<td align="right">Winter 2012
</td>
<td>
<input type="checkbox" name="winter" value="Winter 2012"/>
</td>
<td align="center" width="69"><div align="right">20.00</div></td>
<td><input name="winter2012" type="text" size="5" value="0"/></td>
</tr>
<tr>
<td align="center" colspan="4"><input name="button" type="button" onClick="javascript:display()" value="Submit"/>
<input type="reset" value="Clear Form"/>
</td>
</tr>
</table>
</fieldset>
</form>
Modify these:
Script
var alphanumeric = /^[a-zA-Z0-9\.\,\-\n]+$/;
var quantity = new Array();
quantity[0] = parseInt(document.form1.summer2012.value);
quantity[1] = parseInt(document.form1.autumn2012.value);
quantity[2] = parseInt(document.form1.winter2012.value);
if (quantity[0] > 500 || quantity[1] > 500 || quantity[2] > 500) {
alertmsg = alertmsg + "Please limit each magazine to 500 copies or less:" + "\n";
}
HTML
<td colspan="2"><textarea name="address" cols="30" rows=5 col=40 wrap=soft></textarea>

JavaScript Help! Script not working

I am trying to get this script to work, but it is failing somewhere in the last alert. The script is supposed to pull everything from a form, and then spit out the results as an alert box. I'm pretty sure my html is correct.
function calcServiceTotal() {
var animalName = document.getElementById("name").value;
var ownerName = document.getElementById("owner").value;
var currentDate = document.getElementById("date").value;
var choosenService = document.getElementById("service");
var serviceName = choosenService.options[choosenService.selectedIndex].text;
var serviceCost = document.getElementById("value").value;
var taxCost = serviceCost * 0.07;
var totalCost = serviceCost + taxCost;
if (animalName == null || animalName == "")
{
alert("Please give us your pet's name.");
return false;
}
else if (ownerName == null || ownerName == "")
{
alert("Please give us your name.");
return false;
}
else if (currentDate== null || currentDate == "")
{
alert("Please give us a date.");
return false;
}
else
{
alert("Pet's Name:" + animalName + '\n' + "Owner's Name:" + ownerName + '\n' + "Service:" + choosenService + '\n' + "Cost: $" + serviceCost.toFixed(2) + '\n' + "Tax: $" + taxCost.toFixed(2) + "Total Cost:" + totalCost.toFixed(2));
}
}
Here is the relevant html code.
<table width="339" border="0">
<tr>
<td width="329"><strong>Patient Information</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Name:
<label for="textfield"></label> <input type="text" name="textfield" id="name" /></td>
</tr>
<tr>
<td>Owner:
<input type="text" name="textfield2" id="owner" /></td>
</tr>
<tr>
<td>Date:
<input type="text" name="textfield3" id="date" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><strong>Services</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><form id="form1" name="form1" method="post">
Select a Service:
<label for="select"></label>
<select name="select" id="service">
<option>Basic Appointment - $50</option>
<option>Extended Appointment - $75</option>
<option>Vacination - $25</option>
<option>Grooming - $35</option>
<option>Bathing - $35</option>
</select>
</form></td>
</tr>
<tr>
<td>Service Fee (from above):
<label for="textfield4"></label>
<input type="text" name="textfield4" id="value" />
</td>
</tr>
<tr>
<td><form id="form2" name="form2" method="post" action="">
<input type="button" onclick="calcServiceTotal();" name="button" id="button" value="calculate"/>
</form></td>
</tr>
</table>
The problem is you're using a function that is not defined, namely toFixed()
It is easy to find these errors if you use a debugging tool such as Firebug:
To clarify, toFixed is a function, but even though Javascript is loosely typed, in the context it's supplied your are applying toFixed to a string (for which it is undefined) and in this context the string cannot be coerced into a number.
You must specify it manually, by changing your last alert to:
alert("Pet's Name:" + animalName + '\n' + "Owner's Name:" + ownerName + '\n' + "Service:" + choosenService + '\n' + "Cost: $" + Number(serviceCost).toFixed(2) + '\n' + "Tax: $" + Number(taxCost).toFixed(2) + "Total Cost:" + Number(totalCost).toFixed(2));
Note that there are other errors in your code, such as concatenating two string values (which store Numbers) instead of addition.
I removed some bugs:
function calcServiceTotal() {
var animalName = document.getElementById("name").value;
var ownerName = document.getElementById("owner").value;
var currentDate = document.getElementById("date").value;
var choosenService = document.getElementById("service").value;
var serviceCost = Number(document.getElementById("value").value);
var taxCost = serviceCost * 0.07;
var totalCost = serviceCost + taxCost;
if (animalName == null || animalName == "") {
alert("Please give us your pet's name.");
return false;
} else if (ownerName == null || ownerName == "") {
alert("Please give us your name.");
return false;
} else if (currentDate== null || currentDate == "") {
alert("Please give us a date.");
return false;
} else {
alert("Pet's Name:" + animalName + '\n' + "Owner's Name:" + ownerName + '\n' + "Service:" + choosenService + '\n' + "Cost: $" + serviceCost.toFixed(2) + '\n' + "Tax: $" + taxCost.toFixed(2) + "Total Cost:" + totalCost.toFixed(2));
}
<table width="339" border="0">
<tr>
<td width="329"><strong>Patient Information</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Name:
<label for="textfield"></label> <input id="name" type="text" name="textfield" id="name" /></td>
</tr>
<tr>
<td>Owner:
<input type="text" name="textfield2" id="owner" /></td>
</tr>
<tr>
<td>Date:
<input type="text" name="textfield3" id="date" />
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><strong>Services</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<form id="form1" name="form1" method="post">
Select a Service:
<label for="select"></label>
<select name="select" id="service">
<option value="Basic Appointment - $50">Basic Appointment - $50</option>
<option value="Extended Appointment - $75">Extended Appointment - $75</option>
<option value="Vacination - $25">Vacination - $25</option>
<option value="Grooming - $35">Grooming - $35</option>
<option value="Bathing - $35">Bathing - $35</option>
</select>
</form>
</td>
</tr>
<tr>
<td>Service Fee (from above):
<label for="textfield4"></label>
<input type="text" name="textfield4" id="value" />
</td>
</tr>
<tr>
<td>
<form id="form2" name="form2" method="post" action="">
<input type="button" onclick="calcServiceTotal();" name="button" id="button" value="calculate"/>
</form>
</td>
</tr>
</table>

Categories