Unable to display user data on the textbox - javascript

A parking garage charges a $2.00 minimum fee to park for up to three hours. It charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time.
The web page should calculate the entry hour and minute as well as the exit hour and minute with text boxes. Hours will be entered in a 24 hour format. Once the submit button is selected, the webpage should display the charge, total number of charges and running total of charges. Note that the latter two values will be maintained as the page is used repetedly.
Create and use functions calculateTime and calculateCharge, the former to figure the amount of time in the garage and the latter to figure the charge.
I got the HTML running, however I cannot get the values to display on to the textbox. I also cannot figure out how to calculate the charge. Any help would be appreciated! Thank you.
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>Parking Charge</title>
</head>
<body><div align="center">
<form id="1"><h1><p style="background-color:black ; color:gold;">Parking Garage Charge Calculator</p></h1><hr>
<p>ENTRY TIME: <input type = "number" name = "EntryTime" id = "entTime"></p>
<p>EXIT TIME : <input type="number" id="extTime" name="ExitTime">
<p>Number of Hours Parked: <input type ="number" name="noOfHours" id="nh"><br><br>
<input type="button" id="calculate" name="calc" value="Calculate" onclick="calculateTime()"/>
<input type="reset" id="resetBtn" value="Clear"><br><br>
<input type="number" id="total" name="totalCost" placeholder="Your Total Payment" readonly/><hr>
</form>
</div>
</body>
<script src="P2JS.js"></script>
</html>
JAVASCRIPT CODE:
function calculateTime(){
var EntryTime = document.getElementById('entTime').value;
var ExitTime = document.getElementById('extTime').value;
var noOfHours = (EntryTime - ExitTime);
document.getElementById("nh").innerHTML = noOfHours;
}
/*Function to calculate the payment on the number of hours parked*/
function calculateCharge(){
var charge = 3.50;
var payment = (noOfHours * charge);
if (noOfHours <= 3){
totalPayment = charge * noOfHours;
return payment;
}
else {
payment = ((noOfHours - 3) * (charge + 0.50)) + (charge * 3);
return payment;
}
}

The reason the hours aren't showing is because your are using an input to display it and asking it to show it in the innerHTML which input doesn't have.
So what you want is give it a value instead.
Just add ' value="" ' to your input html
<input type="number" name="noOfHours" value="" id="nh">
and change '.innerHTML' for '.value' in your js.
document.getElementById("nh").value = noOfHours;
You might also want to change your equation for ExitTime - EntryTime because right now it gives you a negative number of hours ;)

Related

Adding a validation for input type, so the user is not allowed to enter anything other than numbers with a min and max value

I'm trying to do this in HTML for now where I have a input field of type=number where I don't want the user to be able to type decimal values/special characters/alphabets at all. I also want the min=30 and max=300so if a user types 29 and clicks else where, the value in the field should change to the min which is 30. If the user types in a value greater than 300 and clicks elsewhere, then I want the value to change to 300 which is the max. I don't want to wait for the user to wait for them to click on a form button. This is what I have so far, where the error is that, the user can still type decimal, and type any value lower than 30. Very new to html/js. Feel free to help me with js implementation if you think that is easier.
<input type="number" min="30" max="300" step="1" oninput="validity.valid||(value=value.replace(/\D+/g, ''))" id="seconds" name="seconds" value="30">
<html>
<script>
function change(){
var inp = document.getElementById("box").value;
inp = Math.floor(inp);
if(inp<30){
document.getElementById("box").value = 30;
}
else if(inp>300){
document.getElementById("box").value = 300;
}
else {
document.getElementById("box").value = inp;
}
}
</script>
<BODY>
<input type= "number" onmouseout = "change()" id ="box"/>
</BODY>
</HTML>
this java script should do
use "onmouseout".

Calculator shows syntax error and referenceError

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cost Calculator</title>
</head>
<body>
<h1>
College Cost Calculator
</h1>
<form>
<input type= "numbers" id= "annualCost" placholder= "annual cost" />
<br>
<input type= "numbers" id= "inflationRate" placholder= "inflationRate" />
<br>
<input type= "numbers" id= "yearsUntilCollege" placholder= "yearsUntilCollege" />
<input id= "button" type="button" value = "Estimate" onclick= "calculator()"/>
<input id= "reset" type="reset" value = "Reset"/>
</form>
<p id= "result">
</p>
<script>
// your code here
document.getElementById(button) = function calculator () {
let inflationRate = document.getElementById(inflationRate);
let annualCost = document.getElementById(annualCost);
let totalCost;
let annualSaving;
let yearsUntilCollege = document.getElementById(yearsUntilCollege);
totalCost = annualCost;
let amount = (inflationRate * annualCost) + annualCost;
totalCost += amount;
amount = ((inflationRate * 2) * annualCost) + annualCost;
totalCost += amount;
amount = ((inflationRate * 3) * annualCost) + annualCost;
totalCost += amount;
annualSaving = totalCost / 5;
return amount
return annualSaving
console.log(`For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`);
console.log(`You have to pay $${totalCost}.`);
console.log(`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`)
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
`You have to pay $${totalCost}.`
`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`
}
</script>
</body>
</html>
This is a code to calculate the college cost for Four(04) years including inflation and how much to save before college begins.
Help me figure out the issue with this code. It keeps giving syntax Error 28:15 and reference Error. I can't seem to figure out what I have done wrong and did I call the function correctly?
Many issues here:
1- Element IDs are strings. Therefore, document.getElementById expects you to pass a string to it, and strings are surrounded by quotation marks (' or ").
2- To get the value of <input> elements, you should use .value. So for example:
//get the value of input with id "inflationRate"
var inflationRate = document.getElementById("inflationRate").value;
3- To call a function on button click, use the button's onclick event, like so:
function calculator() {
//do something...
}
//call the function calculator whenever the button is clicked
document.getElementById("button").onclick = calculator;
4- As pointed out by #ecg8 in the comments, return statements jump out of the function immediately, and therefore you cannot have further statements/computations after the return statement, as they will not be reached.
And as a side note, in your HTML, numeric inputs should have a type of number and not numbers.
Edit: Also, in your last statement here:
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
`You have to pay $${totalCost}.`
`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`
To concatenate these three strings into one, either wrap the entire string (all the lines) into one pair of backticks (`), or use the + operator to concatenate the strings:
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
+ `You have to pay $${totalCost}.`
+ `You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`;
On a final note, all these issues are basic Javascript stuff, so I
would really recommend to study and understand the basics of
Javascript (syntax, functions, events, etc.) before solving problems
like this one.

Through javascript decrease amount in a box and increment the same value decrease to another box dynamically

Here is a sample idea.
Amount - discount = amount paid by the customer.
But the customer pay less and the box due need to be increment dynamically.
Can anyone help me please?
Here is a simple version of what I believe you're asking for:
HTML
Price: <input type="text" id="tb-price" />
Discount (%) <input type="text" id="tb-discount" />
Total: <span id="lbl-total" />
Javascript (jQuery required)
$(function(){
// vars
var $tbPrice = $('#tb-price');
var $tbDisc = $('#tb-discount');
var $lblTotal = $('#lbl-total');
// events
$tbPrice.on('input', calc);
$tbDisc.on('input', calc);
// calculation
function calc(){
var x = $tbPrice.val() * ($tbDisc.val() / 100);
var y = $tbPrice.val() - x;
$lblTotal.html(y);
}
});
Example: http://jsfiddle.net/zkhx1z1d/
Do note that there is no validation here and assumes that the user input is clean. Also this should only be used to show the user what they expect to pay, all calculations should be done/verified by the server as suggested by AlienWebguy

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Create a submit button which will calculate a shipping and handling

I need this code to calculate the sales tax when you hit the submit button and I can't get it to work. I need to figure out how to connect it to the function. Can someone please point out where I am going wrong? I am very new at this and am wondering what I am doing wrong with my code. This is homework, I am not looking for the answer I just need someone to direct me in the right way.Thanx
My assignment is:
Many companies normally charge a shipping and handling fee for
purchases. Create a Web page that allows a user to enter a purchase
price into a text box; include a JavaScript function that calculates
shipping and handling. Add functionality to the script that adds a
minimum shipping and handling fee of $1.50 for any purchase that is
less than or equal to $25.00. For any orders over $25.00, add 10% to
the total purchase price for shipping and handling, but do not include
the $1.50 minimum shipping and handling fee. Th e formula for calculating
a percentage is price * percent / 100. For example, the formula
for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which
results in a shipping and handling fee of $5.00. After you determine
the total cost of the order (purchase plus shipping and handling),
display it in an alert dialog box.
Here is my Code: I need this code to calculate the sales tax when you hit the submit button and I can't get it to work. Can someone please point out where I am going wrong?
Code:
<script type="text/javascript">
/*<![CDATA [*/
//Shipping & handling fee
var price=[];
var shipping=calculateShipping(price);
var total=price+shipping;
function calculateShipping()
{
var num = new Number(price);
//This will add $1.50 to any purchases that are less than or equal to $25.00.
if (num <= 25){
return 1.5;
//Here 10% will be added to any purchase that is greater than $25.00 but do not inlcude the
$1.50 fee.
} else{
return num * 10 / 100;
}
}
window.alert("Your total is $" + total + ".")
/* ]]> */
</script>
</head>
<body>
<h1>Enter Purchase Price Here</h1>
<script type="text/javascript">
/* <![CDATA[ */
document.write(parseFloat");
if(price <=25.00){var shipping=1.50}
else{var shipping=price*(10/100)};
var total=(price+shipping).toFixed(2);
/* ]]> */
</script>
<form id="btncalcprice" action="submit-form.php">
<input type='text' name='query'>
</form>
<form>
<input type="button" value="Submit" onClick="alert('YOUR total is $'); return true">
</form>
</body>
EDIT: Reviewed Code
You have some syntax issues in your code, additionally the methodology you were following was not quite correct. You need to call the function from the button onclick event, then run your JavaScript. You will find what you need in the updated code example below. Make note that I used parseFloat instead of parseInt in order to incorporate decimals...
<script type="text/javascript">
/*<![CDATA [*/
function calculateShipping() {
var price = document.getElementById('price').value;
//This will add $1.50 to any purchases that are less than or equal to $25.00.
if (price <= 25){
price=parseFloat(price) + 1.5;
} else {
//add 10%
var percentToAdd=parseFloat(price) * .1;
price=parseFloat(price)+parseFloat(percentToAdd);
}
document.getElementById('result').innerHTML='Total shipping cost: '+price;
}
/* ]]> */
</script>
</head>
<body>
<h1>Enter Purchase Price Here</h1>
<div id="result"></div>
<input type="text" name="price" id="price">
<input type="button" value="Submit" onClick="calculateShipping(); return false;">
</body>
First of all you dont need the form action if you are just calling a function, secondly if you want to prevent the default submit of the form, then return false in your onclick... it should look like this:
onclick="calculateShipping(); return false;"

Categories