I am new In jquery created validation and calculation using formula.I have created six input fields.created validation all fields.but when empty all fields click calculation red star symbol showing first two fields not showing remain four fields please help me friends
here my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function calculate() {
var answer = 0;
if (validate()) {
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA && valueB && valueC && valueD && valueE && valueF) {
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC)) + (parseFloat(valueF / valueE))) / 3;
}
else {
if (valueA && valueB && valueC && valueD)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC))) / 2;
else {
if (valueA && valueB && valueE && valueF)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueF / valueE))) / 2;
else (valueA && valueB)
answer = ((parseFloat(valueB / valueA)));
}
}
if (parseFloat(answer) > .0238)
alert("Your Effective Rate = " + parseFloat(answer * 100).toFixed(2));
else if (answer == 0)
alert("Your Effective Rate:0.00% ");
else
alert("Oops, something has gone terribly wrong!Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis");
}
return false;
}
function validate() {
var status = false;
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
status = true;
$("#spanb").hide();
}
else {
status = false;
$("#spanb").show();
}
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
if (valueE && !valueF) {
status = false;
$("#spanf").show();
$("#spane").hide();
}
if (!valueE && valueF) {
status = false;
$("#spane").show();
$("#spanf").hide();
}
if (valueC && valueD) {
$("#spand").hide();
$("#spanc").hide();
return true;
}
if (valueE && valueF) {
status = true;
$("#spane").hide();
$("#spanf").hide();
}
return status;
}
</script>
</head>
<body>
<form>
<table class="calculator" border='0' width='500px' cellpadding='3' cellspacing='1'
class="table">
<tr class="calcheading">
<td colspan="3" align="center">
Whats your effective rate?
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 1</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuea' id="valuea" onkeypress="return isNumber(event)"
autocomplete="off" />
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spana">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valueb' id="valueb" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanb">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 2</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuec' id="valuec" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanc">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valued' id="valued" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spand">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 3</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuee' id="valuee" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spane">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valuef' id="valuef" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanf">*</span>
</td>
</tr>
<tr class="submit">
<td colspan="3" align="center">
<input type='submit' value='Calculate' onclick="return calculate();" />
</td>
</tr>
<tr class="calcrow">
<td colspan="3" align="center">
</td>
</tr>
</table>
</form>
</body>
</html>
calculation all working good.when leave fields empty click calculation show red star required first two column remain not showing help me friends
There is a mistake in the condition you have written for the valueC,valueD, valueE and valueF. You should continue as of valueA and valueA for the remaining too, if you want to achieve the functionality as you are trying to.
But, My Suggestion is to Use http://jqueryvalidation.org/ Plugin for validating the elements. It is very handy to use and customize as required.
Thank you
Check you conditions. small logical mistakes in your conditions. for eg.
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
This will check if either valuec or valued is empty. You are not checking for both empty. You need to add something like this
if (!valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
Brother its not a good trick to make your code lengthy. You could achieve your goal by using each function. Below is an example of doing that. Please have a look.
function validate(){
var formValidate = true;
jQuery(form + " select," + form + " input").each(
function (index) {
var input = jQuery(this);
if (input.val() == "" ) {
input.addClass("error");
input.parent().next("td").fadeIn("slow");
}
else {
input.removeClass("error");
input.parent().next("td").fadeOut("slow");
}
if (input.hasClass('error')) {
if (formValidate == true) {
formValidate = false;
}
}
}
);
if (formValidate == true) {
return true;
}
else {
return false;
}
}
exact solution to your answer is below please copy n paste then check.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../jQuery/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function calculate() {
var answer = 0;
if (validate()) {
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA && valueB && valueC && valueD && valueE && valueF) {
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC)) + (parseFloat(valueF / valueE))) / 3;
}
else {
if (valueA && valueB && valueC && valueD)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC))) / 2;
else {
if (valueA && valueB && valueE && valueF)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueF / valueE))) / 2;
else (valueA && valueB)
answer = ((parseFloat(valueB / valueA)));
}
}
if (parseFloat(answer) > .0238)
alert("Your Effective Rate = " + parseFloat(answer * 100).toFixed(2));
else if (answer == 0)
alert("Your Effective Rate:0.00% ");
else
alert("Oops, something has gone terribly wrong!Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis");
}
return false;
}
function validate() {
var status = false;
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
status = true;
$("#spanb").hide();
}
else {
status = false;
$("#spanb").show();
}
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
if (valueE && !valueF) {
status = false;
$("#spanf").show();
$("#spane").hide();
}
if (!valueE && valueF) {
status = false;
$("#spane").show();
$("#spanf").hide();
}
if (valueC && valueD) {
$("#spand").hide();
$("#spanc").hide();
return true;
}
if (valueE && valueF) {
status = true;
$("#spane").hide();
$("#spanf").hide();
}
//change is here
//change status value as per your requirement
if (!valueC && !valueD) {
//status = false;
$("#spand").show();
$("#spanc").show();
}
if (!valueE && !valueF) {
//status = false;
$("#spanf").show();
$("#spane").show();
}
return status;
}
</script>
</head>
<body>
<form>
<table class="calculator" border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading">
<td colspan="3" align="center">
Whats your effective rate?
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 1</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuea' id="valuea" onkeypress="return isNumber(event)"
autocomplete="off" /></td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spana">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valueb' id="valueb" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanb">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 2</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuec' id="valuec" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanc">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valued' id="valued" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spand">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 3</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuee' id="valuee" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spane">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valuef' id="valuef" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanf">*</span>
</td>
</tr>
<tr class="submit">
<td colspan="3" align="center">
<input type='submit' value='Calculate' onclick="return calculate();" />
</td>
</tr>
<tr class="calcrow">
<td colspan="3" align="center">
</td>
</tr>
</table>
</form>
</body>
</html>
If you really want to do it in that way consider below validation method.
I assume what you want is to check the input fields are empty or not. what you have done is still unclear to me.
To do a proper validation you need to identify and state what should be checked and how should they handled as well.
function validate() {
var status = false;
var valueA = $("#valuea").val();
var valueB = $("#valueb").val();
var valueC = $("#valuec").val();
var valueD = $("#valued").val();
var valueE = $("#valuee").val();
var valueF = $("#valuef").val();
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
$("#spanb").hide();
status = true;
}
else {
$("#spanb").show();
status = false;
}
if (valueC) {
$("#spanc").hide();
status = true;
}
else {
$("#spanc").show();
status = false;
}
if (valueD) {
$("#spand").hide();
status = true;
}
else {
$("#spand").show();
status = false;
}
if (valueE) {
$("#spane").hide();
status = true;
}
else {
$("#spane").show();
status = false;
}
if (valueF) {
$("#spanf").hide();
status = true;
}
else {
$("#spanf").show();
status = false;
}
return status;
}
Related
I am in the process of writing a webpage. I have everything done that is needed, however, when you enter any quantity over 30 it will make the id = "shipping" color red. It does this but it does it for anything less than 30 as well. Also I am having trouble with my submit button sending off to a server/url. Any help is appreciated! I will attach my code!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Widgets R' Us </title>
<style>
table,
td {
border: 1px solid black;
}
</style>
<script type="text/javascript">
//Check if non -number or a negative number
function realNumber() {
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
//isNaN is a predetermined function
if ((isNaN(qty1) || qty1 < 0) || (isNaN(qty2) || qty2 < 0) || (isNaN(qty3) || qty3 < 0)) {
alert("The quantity given is not a real number or is a negative number!");
return false; //Will not allow for data to go to server.
} else {
return true;
}
}
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
} else {
document.getElementById("shipping").style.color = "black";
}
}
}
function checkOut() {
if (total()) {
if ((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked)) {
return true;
}
}
return false;
}
</script>
</head>
<body>
<div>
<h1><b><big> Widgets R' Us </b></strong>
</h1>
<h2><b> Order/Checkout </b></h2>
<form name "widgets" onsubmit="return checkOut();" action="https://www.reddit.com/" method="get">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" /</td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" /</td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Product Total:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()" /> </td>
</tr>
</form>
</body>
</html>
Problem with your values qty1,qty2,qty3. these values are reading as string. so instead of addding these values , its concatinating the strings. replace
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
with
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
It will Solve your problem with 'Red'.
For the submit button, function total() is not returning anything. so change something like
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
return true;
} else if(over>0) {
document.getElementById("shipping").style.color = "black";
return true;
}else{
document.getElementById("shipping").style.color = "black";
return false;
}
}
}
and checkout() as
function checkOut() {
if (total()) {
if (((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked))||
(document.getElementById("shipping").style.color != "red")) {
return true;
}
}
return false;
}
Replace
var over = qty1 + qty2 + qty3;
With
var over = parseInt(qty1) + parseInt(qty2) + parseInt(qty3);
There were some minor HTML errors but the real issue is that numeric strings were being concatenated. So, to get the quantity values you need to use parseInt() to extract the integer value so that math is performed instead of string concatenation. Also, it's a little odd that the user has to click the Calculate Button in order to see a total. The button does work correctly, but is this what you really want?
One more thing, as tempting as it may be to directly alter the color of elements with JavaScript, in terms of keeping the code more robust, it is preferable to simply change the class name as the code does in this example since I created two classes in the CSS for this purpose.
The form now submits as long as the checkbox is unchecked and the units do not exceed 30. I changed the method to "post" and adjusted the true/false return statements in checkOut(). Note when data is submitted using the POST method, then no form data appears appended to the URL; for more info see here. I also altered the totals() function so that now it returns a value, namely the total price.
var d = document;
d.g = d.getElementById;
var qty = [0, 0, 0, 0];
var shipping = d.g("shipping");
function realNumber() {
var qtyInvalid = [0, 0, 0, 0];
for (let i = 1, max = qtyInvalid.length; i < max; i++) {
qtyInvalid[i] = (isNaN(qty[i]) || qty[i] < 0);
}
if (qtyInvalid[1] || qtyInvalid[2] || qtyInvalid[3]) {
console.log("The quantity given is not a real number or is a negative number!");
return false;
}
return true;
}
function total() {
var over = 0;
var price = [0, 0, 0, 0];
for (j = 1, max = price.length; j < max; j++) {
price[j] = d.g("Price" + j + "").value;
qty[j] = d.g("Quantity" + j + "").value;
}
var totals = 0;
var yes = 0;
const radix = 10;
for (q = 1, max = qty.length; q < max; q++) {
over += parseInt(qty[q], radix)
}
//console.log(over);
if (!realNumber()) {
return false;
}
for (let k = 1, max2 = price.length; k < max2; k++) {
totals += (price[k] * qty[k]);
}
yes = (totals).toFixed(2);
d.g("ProductTotal").innerHTML = "$" + yes;
shipping.className = (over > 30) ? "red" : "black";
return totals;
} // end total
function checkOut() {
var retval = false;
var shippingIsRed = (shipping.className == "red");
var extraChecked = d.g("extra").checked;
if ( total() ) {
retval = (!shippingIsRed && !extraChecked)? true : false;
}
return retval;
} //end checkout
h1 {
font: 200% Arial, Helvetica;
font-weight: bold;
}
h2 {
font-weight: bold;
}
table,
td {
border: 1px solid black;
}
p.red {
color: #f00;
}
p.black {
color: #000;
}
<div>
<h1>Widgets R' Us</h1>
<h2>Order/Checkout</h2>
<form name="widgets" onsubmit="return checkOut()" action="https://www.example.com/" method="post">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" </td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" </td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Total Price:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping" class="black">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()"> </td>
</tr>
</form>
I also removed some unnecessary repetitive code that fetches the quantity values, taking advantage of JavaScript closures and for-loops.
Good evening! I'm teaching myself to code. Right now, I'm making a JavaScript loan calculator, but I hit a snag. If I put 0% interest, it displays nothing in my output textboxes. Everything else is working perfectly though. Any help would be appreciated. Thanks!
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Loan Calculator</title>
<style type="text/css">
.auto-style1 {
text-align: left;
}
.auto-style2 {
font-size: larger;
color: #FFF;
font: Georgia;
}
.auto-style3 {
width: 82px;
text-align: center;
style="float: right;
}
table {
background-color: #F5F5F5;
width: 400px;
height: 300px;
padding-left: 20px;
padding-bottom: 20px;
padding-top: 20px;
}
body {
background-color: #d2691e;
}
</style>
</head>
<body>
<form name="loaninfo">
<div class="auto-style1">
<p><strong>
<span class="auto-style2"> </span></strong><strong><span class="auto-style2"><br />
</span></strong></p>
</div>
<table width="327">
<tr><td colspan="3"></td></tr>
<tr>
<td>Loan Amount:</td>
<td>
$
<input type="text" name="principal" size="12" title="textfield" pattern="([0-9]+\.)?[0-9]+" >
</td>
</tr>
<tr>
<td>Interest Rate:</td>
<td>
<input type="text" name="interest" size="12" title="textfield" pattern="([0-9]+\.)?[0-9]+" >
%
</td>
</tr>
<tr>
<td>Number of Years for Loan:</td>
<td>
<input type="text" name="years" size="12" title="textfield" pattern="([0-9]+\.)?[0-9]+" >
</td>
</tr>
<tr>
<td colspan="3"><input type="button" class="auto-style3" onClick="calculate();" value="Calculate">
<br />
<br />
</td>
</tr>
<tr>
<td colspan="3">
<b>Your Payment Information</b>
</td>
</tr>
<tr>
<td>Monthly Payment Amount:</td>
<td>$ <input type="text" name="payment" size="12" readonly /></td>
</tr>
<tr>
<td>Total Payment Amount:</td>
<td>$ <input type="text" name="total" size="12" readonly ></td>
</tr>
<tr>
<td>Total Interest Payments:</td>
<td>$ <input type="text" name="totalinterest" size="12" readonly /> </td>
</tr>
<tr>
<td colspan="3">
<input type="reset" class="auto-style3" />
</td>
</tr>
</table>
</form>
<script language="JavaScript">
function calculate() {
var principal = document.loaninfo.principal.value;
var months_in_year = 12
var interest = document.loaninfo.interest.value / 100 / months_in_year;
var payments = document.loaninfo.years.value * months_in_year;
var x = Math.pow(1 + interest, payments);
var monthval = (principal*x*interest)/(x-1);
if (!isNaN(monthval) &&
(monthval != Number.POSITIVE_INFINITY) &&
(monthval != Number.NEGATIVE_INFINITY)) {
document.loaninfo.payment.value = round(monthval);
document.loaninfo.total.value = round(monthval * payments);
document.loaninfo.totalinterest.value = round((monthval * payments) - principal);
}
else {
document.loaninfo.payment.value = "";
document.loaninfo.total.value = "";
document.loaninfo.totalinterest.value = "";
}
function round(x) {
return Math.round(x*100)/100;
}
function jsDecimals(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if ((key < 48 || key > 57) && (key < 96 || key > 105)) {
if (!jsIsUserFriendlyChar(key, "Decimals")) {
return false;
}
}
else {
if (evt.shiftKey) {
return false;
}
}
}
return true;
}
form.onsubmit = function () {
return textarea.value.match(/^\d+(\.\d+)?$/);
}
</script>
When you put 0 you are getting
var x = Math.pow(1 + interest, payments); // 1
var monthval = principal * x * interest / (x - 1); //NaN because 1-1 in fraction is 0 so it returns 0/0 and it's NaN
you can change you code to be like this:
if (interest===0){
var monthval = (principal)/(months_in_year);
} else {
var monthval = (principal*x*interest)/(x-1);
}
Working Version: http://codepen.io/mhadaily/pen/ZpypdA
feel free to change it to be like what you want.
It's because of this section of code.
else if (interest == 0) {
document.loaninfo.payment.value = "";
document.loaninfo.total.value = "";
document.loaninfo.totalinterest.value = "";
}
When the interest is 0, you are setting the values of all your output boxes to an empty string.
You should replace the RHS of the assignment.
Hi and sorry for my bad English
I have a contact page and i am using javascript to make a "captcha". so peaople must make a math and if thats correct they can send me a e-mail. Now my problem is that javasctipt give a alert that the math is wrong or not filled but the e-mail is still seended.
my html:
<script type="text/javascript">
function validate () {
var ta = document.getElementById("ta").value;
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1+ digit2;
if (answer === null || answer === "") {
alert("reken de cijfers uit");
return false;
} else if (answer != sum){
alert("je som is fout");
} else if (ta === null || ta === ""){
alert("schrijf een bericht");
} else {
document.getElementById("answer").innerHTML = "bezig met sturen";
document.getElementById("answer").innerHTML = "";
}
}
function randNums () {
var rand_num1 = Math.floor(Math.random()*10)+1;
var rand_num2 = Math.floor(Math.random()*10)+1;
document.getElementById("digit1") .innerHTML=rand_num1;
document.getElementById("digit2") .innerHTML=rand_num2;
}
</script>
<body onload="randNums() ;">
<form action="/cgi-bin/form.cgi" method="POST" onsubmit="return validate ();">
<input type="hidden" name="DEBUG" value="0">
<input type="hidden" name="MAILFILE" value="peymankarimi/form/sjabloon.txt">
<input type="hidden" name="MAILTO" value="peyman_50#hotmail.com">
<input type="hidden" name="REPLYFAULT" value="peymankarimi/form/formulier.html">
<input type="hidden" name="REPLYOK" value="peymankarimi/form/verzonden.html">
<table border="0" width="374" id="contactformulier">
<tr>
<td width="137">Naam:</td>
<td width="230"><input type="text" size="31" name="naam" placeholder="Naam"></td>
</tr>
<tr>
<td width="137">Voornaam:</td>
<td width="230"><input type="text" size="31" name="voornaam" placeholder="Voornaam"></td>
</tr>
<tr>
<td width="137">Woonplaats:</td>
<td width="230"><input type="text" size="31" name="woonplaats" placeholder="Woonplaats"></td>
</tr>
<tr>
<td width="137">Telefoonnummer:</td>
<td width="230"><input type="text" size="31" name="telefoon" placeholder="Telefoonnummer"> </td>
</tr>
<tr>
<td width="137">E-mailadres: <br></br></td>
<td width="230">
<input type="text" size="31" name="MAILFROM" placeholder="E-mailadres"> <br></br> </td>
</tr>
</tr>
<tr>
<td width="137">Onderwerp:</td>
<td width="230"><input type="text" size="31" maxlength="30" name="SUBJECT"> </td>
</tr>
<tr>
<td colspan="2">Uw vragen, opmerkingen, suggesties, ... :<br>
<textarea id="ta" name="omschrijving" rows="6" cols="43" ></textarea>
<br />
<strong> Tel deze cijfers op </strong>
<span id="digit1"> </span> +
<span id="digit2"> </span> =
<input type="text" id="answer" size="2"; />
<br />
<p align="right"><input type="submit" name="cmdVerzenden" value="Verzenden">
<input type="reset" name="cmdWissen" value="Wissen"></td>
</form>
</tr>
</table>
</form>
</body>
Your validate function needs to return false on all errors to stop the form from submitting. You only seem to have it for one error.
function validate () {
var ta = document.getElementById("ta").value;
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1+ digit2;
if (answer === null || answer === "") {
alert("reken de cijfers uit");
return false;
} else if (answer != sum){
alert("je som is fout");
return false;
} else if (ta === null || ta === ""){
alert("schrijf een bericht");
return false;
} else {
document.getElementById("answer").innerHTML = "bezig met sturen";
document.getElementById("answer").innerHTML = "";
}
}
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>
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>