Javascript Shipping Calculator Not Grabbing Input - javascript

I am getting the headache of a lifetime. I'm not too great with Javascript so I have no idea what's going on. I'm supposed to be coding a text box that when a price is entered and submitted it will calculate the shipping and tell you the total. Everything is working except for the fact that the typed value isn't being set. So the price seems to be permanently set at NaN no matter what is inputted. What am I doing wrong? D:
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post" name="number" onsubmit='window.alert("Your total is $" + total + ".");'>
<input type="text" name="purchasePrice" placeholder="0.00" />
<input type="submit" value="submit" />
</form>
<script>
/* <![CDATA[ */
var price = parseFloat(document.getElementsByTagName("input")[0].value);
var shipping = parseFloat(calculateShipping(price));
var total = price + shipping;
function calculateShipping(price) {
if (price <= 25) {
return 1.5;
} else {
return price * 10 / 100
}
}
/* ]]> */
</script>
</body>
</html>

Here is a sample which may help you
<input id="amount" type="text" name="purchasePrice" placeholder="0.00" />
<input id="submit" type="submit" value="submit" />
var amount = document.getElementById("amount");
var submit = document.getElementById("submit");
function calculateShipping() {
var price = parseFloat(amount.value) || 0;
if (price <= 25) {
alert("Your total is $" + 1.5);
} else {
alert("Your total is $" + (price * 10 / 100));
}
}
submit.addEventListener("click", calculateShipping, false);
on jsfiddle

JavaScript code runs before it knows price... so anything *,+ NaN is... NaN.
You should call calculation of total while submit is clicked, f.ex. this way:
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post" name="number" onsubmit='calculateTotal()'>
<input type="text" name="purchasePrice" placeholder="0.00" />
<input type="submit" value="submit" />
</form>
<script>
/* <![CDATA[ */
function calculateTotal() {
var price = parseFloat(document.getElementsByTagName("input")[0].value);
var shipping = parseFloat(calculateShipping(price));
var total = price+shipping;
window.alert("Your total is $" + total + ".");
}
function calculateShipping(price) {
if (price <= 25) {
return 1.5; }
else {
return price * 10/100 }
}
/* ]]> */
</script>
</body>
</html>

You need to attach an event handler that fires when the user enters a value.
<form method="post" name="number" onsubmit='window.alert("Your total is $" + total + ".");'>
<label for="purchasePrice">Price:</label>
<input type="text" name="purchasePrice" id="purchasePrice" placeholder="0.00" />
<br>
<label for="shipping">Shipping:</label>
<input type="text" name="shipping" id="shipping" disabled>
<!-- <input type="submit" value="submit" /> -->
</form>
<script>
var price;
var shipping = parseFloat(calculateShipping(price));
var total = price+shipping;
function calculateShipping(price) {
if (price <= 25) {
return 1.5; }
else {
return price * 10/100;
}
}
var pp = document.getElementById("purchasePrice");
pp.onkeyup = function(e){
price = calculateShipping(this.value);
document.getElementById("shipping").value = price;
};
</script>
This kind of thing really is easier with a library like jQuery. It also handles the differences between browser implementations for attaching event handlers.

Related

javascript event handler not working (button click - google says null)

I've looked over a number of threads here of similar problems to little avail - I can't figure out exactly what's going wrong here. Google claims that the element I'm trying to reference is null
Uncaught TypeError: Cannot read property 'addEventListener' of null at sales.js:12
and no matter how I've tried to fix it, it doesn't seem to work. As you can see in the js code, I've tried a number of ways of fixing it based on stuff I've found here.
Originally the <script src ="sales.js"> in the HTML file was up in the head, but I read in some pages here that putting it there can make it load before everything else and to put it down before the HTML closing tag.
Any suggestions?
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<main>
<h1>Sales Calculator</h1>
<p>Complete the form and click "Calculate".</p>
<fieldset>
<legend>
Item Information
</legend>
<label for="item">Item:</label>
<input type="text" id="item" ><br>
<label for="price">Price:</label>
<input type="text" id="price" ><br>
<label for="discount">Discount %:</label>
<input type="text" id="discount" ><br>
<label for="taxRate">Tax Rate:</label>
<input type="text" id="taxRate" ><br>
<label for="total">Discount Price:</label>
<input type="text" id="discountPrice" disabled ><br>
<label for="salesTax">Sales Tax:</label>
<input type="text" id="salesTax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br><br>
<div id="buttons">
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br></div>
</fieldset>
<pre>© Fall 2020 Rob Honomichl - Dakota State University</pre>
</main>
</body>
<script src="sales.js"></script>
</html>
JS Code:
//"use strict"
var $ = function (id) {
return document.getElementById(id);
};
//window.addEventListener("DOMContentLoaded", () => {
//$("#calculate").addEventListener("click", processEntries);
//});
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("#calculate").addEventListener("click", processEntries);
});
//window.onload = function(){
//$("#calculate").addEventListener("click", processEntries);
//};
const processEntries = () => {
//Gather User Input
//var item = document.querySelector("#item").value;
var price = parseFloat(document.querySelector("#price").value).toFixed(2);
var discount = parseInt(document.querySelector("#discount").value);
var taxRate = parseInt(document.querySelector("#taxRate").value);
//Calculate Discounted Price
function discountPriceCalc(price, discount) {
const disPrice = price * (discount/100);
return disPrice.toFixed(2);
}
//Calculate Sales Tax
function salesTaxCalc(discountPrice, taxRate) {
const taxTotal = price * (taxRate/100);
return taxTotal.toFixed(2);
}
//Calculate Total
function totalCalc(discountPrice, salesTax) {
return ((Number(discountPrice) + Number(salesTax).toFixed(2)));
}
//Calculate the disabled text box values
var discountPrice = discountPriceCalc(price, discount);
var salesTax = salesTaxCalc(discountPrice, taxRate);
var Total = totalCalc(discountPrice, salesTax);
//Update Text Boxes
document.getElementById("discountPrice").value = discountPrice;
document.getElementById("salesTax").value = salesTax;
document.getElementById("total").value = Total;
//set focus to Item box after
document.getElementById("item").focus();
};
You need to get rid of the # in the getElementById call to properly locate the element.
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("calculate").addEventListener("click", processEntries);
});

Program returning values as NaN

Im trying to get this program to work and i have everything running, but my values return as NaN. I've tried initializing the variables as numbers both in and outside the function to no avail. Any help?
EDIT: added in the entire script, html and all incase it helps alongside the edits suggested thus far.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>Placeholder</title>
</head>
<body>
<header>
<h1>Resturant Calculator</h1>
</header>
<article>
<fieldset>
<label for="bill">
Bill Amount
</label>
<input type="number" id="bill" />
</fieldset>
<fieldset>
<label for="tip">
Tip Percent
</label>
<input type="number" id="tip" />
<label>(enter as whole number)</label>
</fieldset>
<fieldset>
<label for="peeps">
# of people
</label>
<input type="number" id="peeps" />
</fieldset>
<button id="submit" onclcick="calculate()">Calculate</button>
<p id="tipAmount">Tip Amount:</p>
<p id="total">Total Bill:</p>
<p id="totalByPeep">Total per Person:</p>
</article>
<script>
"use strict"
var bill = document.getElementById("bill").value;
var tip = document.getElementById("tip").value;
var peeps = document.getElementById("peeps").value;
var total;
var totalTip;
var tpPerson;
function calculate(){
totalTip = bill.value / (tip.value * 0.01);
total = bill.value + totalTip;
tpPerson = total / peeps.value;
document.getElementById("tipAmount").innerHTML = "Tip Amount: " + totalTip;
document.getElementById("total").innerHTML = "Total: " + total;
document.getElementById("totalByPeep").innerHTML = "Total per Person: " + tpPerson;
}
function createEventListener(){
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener){
submitButton.addEventListener("click", calculate, false);
}
else if(submitButton.attachEvent){
submitButton.attachEvent("onclick", calculate);
}
}
if (window.addEventListener){
window.addEventListener("load", createEventListener, false);
}
else if (window.attachEvent){
window.attachEvent("onload", createEventListener);
}
</script>
</script>
</body>
</html>
You need to get the values from the elements bill,tip,peeps
Probably something like document.getElementById("bill").value
Using just document.getElementById("bill") you are selecting the element, but not its value
You need to read the value inside calculate()
function calculate(){
bill = +bill.value, tip = +tip.value, peeps = +peeps.value;
totalTip = bill/ (tip * 0.01);
total = bill + totalTip;
tpPerson = total / peeps;
document.getElementById("tipAmount").innerHTML = "Tip Amount: " + totalTip;
document.getElementById("total").innerHTML = "Total: " + total;
document.getElementById("totalByPeep").innerHTML = "Total per Person: " + +tpPerson;
}

When I click the Calculate button, it does not display the calculations in textbox for sales tax and total

When I run the code on my chrome browser, clicking the calculate button, it does not put the value in the Total and Sales Tax text box.
Also "Add the Javascript event handler for the click event of the Clear button, This should clear all text boxes and move the cursor to the Subtotal field."
I'm using Html and js file. Using a function expression to calculate and display my calculation, then also use the clear button to clear all text boxes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
This is my js file.
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.
")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = sumSalesTax;
};
Sales Tax Calculator
It seems like you had a typo when you were doing $("clear").onclick = sumSalesTax;, as the variable was named SumSalesTax rather than with the lower case. This meant that the code block errored out and therefore didn't actually run. Make sure you make good use of the browser console so you can spot errors like this! The below example should work
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = SumSalesTax;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>

Using JavaScript to store user input from a form into an array of records

This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>

HTML onclick isn't running function

I am new to Javascript and just getting into it for my web design class. I am working on a project with Javascript inside HTML. I have it all written, but the HTML doesn't seem to call the Javascript function. I've been searching for a solution but can't seem to get anything to work. The code is:
<html>
<head>
<script>
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
message-box ("Invalid data for principle amount.");
}
}
else {
message-box ("Invalid data for interest rate.");
}
}
</script>
<style>
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
</style>
</head>
<body>
<form>
Enter Principal Ammount : <input type="text" id ="principal" />
</br>
Enter Intrest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Ammount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick=calculateInterest()/> </br>
</form>
</body>
</html>
The browser error is "SyntaxError: expected expression, got '}' " on line 2 but I just can't see what the issue is. Any help is greatly appreciated!
Side note, I am aware there are some weird spelling mistakes. My instructor is from India and not totally fluent in English. She made the HTML file for us to use and we just have to put in the Javascript.
There is no message-box function. Did you mean alert()? Your code currently works, with those changes:
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
alert("Invalid data for principle amount.");
}
}
else {
alert("Invalid data for interest rate.");
}
}
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
<form>
Enter Principal Amount : <input type="text" id ="principal" />
</br>
Enter Interest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Amount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick="calculateInterest()" /> </br>
</form>
Small Nitpick: Fixed some small typos not related to code. Ammount => Amount. Intrest => Interest.

Categories