How to calculate the total price automatically using Javascript? - javascript

I created a form of ticket ordering. I have to calculate the total price of purchasing the adult and discount (child and senior) tickets.
Here is the html code.
<form action="">
<p>Adult: $<span class="price-adult">52</span></p>
<p>Discount (3 - 11 years old; 65 years old or above): $<span
class="price-discount">23</span> </p>
<label for="num-adult">Number of Visitor (Adult):</label>
<input type="number" id="num-adult" name="num-adult" min="1" max="50"
value="1"><br><br>
<label for="num-discount">Number of Visitor (Discount):</label>
<input type="number" id="num-discount" name="num-discount" min="1" max="50"
value="1"><br><br>
<p>Total Amount: $ <span class="total"></span> </p>
<input type="submit" value="Submit">
</form>
Here is the Javascript code that I have written. I tried to write the adult version first so the discount ticket is not included in the JS code. Please help me find the problem.
let numOfadult = document.getElementById("num-adult").value
const priceOfAdult = document.getElementsByClassName("price-adult").value
function getTotalPrice() {
let total = numOfadult * priceOfAdult
document.getElementsByClassName('total').textContent = total
}
getTotalPrice()

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="">
<p>Adult: $<span class="price-adult" id="price-adult" >52</span></p>
<p>Discount (3 - 11 years old; 65 years old or above): $<span
class="price-discount">23</span> </p>
<label for="num-adult">Number of Visitor (Adult):</label>
<input type="number" id="num-adult" name="num-adult" min="1" max="50"
value="1" onkeyup="sum();"><br><br>
<label for="num-discount">Number of Visitor (Discount):</label>
<input type="number" id="num-discount" name="num-discount" min="1" max="50"
value="1"><br><br>
<p>Total Amount: $ <span class="total" id="total"></span> </p>
<input type="submit" value="Submit">
<script>
function sum()
{
var txtFirstNumberValue = document.getElementById('num-adult').value;
var txtSecondNumberValue = document.getElementById('price-adult').innerHTML;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result))
{
document.getElementById('total').innerHTML = result;
}
}
</script>
</form>
</body>
</html>

Related

How do I use checkboxes to convert currencies (moneys) from US to whatever the user has checked with Jquery/Inputs

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="Author" content="Micah Cave">
<title>Ice 11</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#convert").click( function() {
var dollarAmount = $('input:text').val();
if ( $("#usa").is(':checked') )
dollarAmount = dollarAmount*1;
if ( $("#russia").is(':checked') )
dollarAmount = dollarAmount * 73.18;
});
});
</script>
</head>
<body>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>
</body>
</html>
So I need to take the value that's entered in the input box above, and then if they check off any box(s) to then convert each checked boxs currency from US to whatever was selected, and then print out the results each time using if statements.
you can make a function called convert,when convert button click or checkbox click then call that function.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="Author" content="Micah Cave">
<title>Ice 11</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#convert").click(convert);
$("input:checkbox").click(convert)
});
function convert(){
var dollarAmount = $('input:text').val();
var result = " "
if ( $("#usa").is(':checked') )
result += dollarAmount*1 + ";";
if ( $("#russia").is(':checked') )
result += dollarAmount * 73.18 + ";";
$("#pasteHere").text(result)
}
</script>
</head>
<body>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>
</body>
</html>
That is my solution:
$(document).ready(function() {
let selectedCurrencies = [];
$("#convert").click(function() {
let dollarAmount = $('input:text').val();
let checkBoxList = $('input:checked');
let resultText = "";
for (let i = 0; i < checkBoxList.length; i++) {
resultText += "US "+dollarAmount+" dollar =";
switch (checkBoxList[i].id) {
case 'usa':
resultText += dollarAmount * 1;
break;
case "russia":
resultText += dollarAmount * 73.18;
break;
}
resultText+=" "+(checkBoxList[i].nextSibling.textContent)+"<br>";
}
$("#pasteHere").html(resultText);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>

how to iterate through HTML elements and sum the values using for loop

i have an issue using for loop to sum the values through elements inside HTML by pressing button but the code did not work correctly also i tried to show alert a massage that says "not a number" but every time show the same massage once i press the button
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="inp" type="" placeholder="Enter a Number " >
<input class="inp" type="" placeholder="Enter elec" >
<input class="inp" type="" placeholder="Enter food " >
<input class="inp" type="" placeholder="Enter car " >
<input class="inp" type="" placeholder="Enter resturent " >
<h1 class="total">total</h1>
<button class="btn">calculate</button>
<script
const btn= document.querySelector('.btn')
const total = document.querySelector('.total')
const inp = document.querySelectorAll('.inp')
btn.addEventListener('click',function(){
if (isNaN(inp.value)) {
alert("Not a number")
console.log(inp.value);
} if (inp.value === ""){
alert("enter number ")
}
for (let i = 0; i <inp.length; i++) {
let index = 0
const current = index + inp[i].value
total.innerHTML = index
}
})
</script>
</body>
</html>
Change to input type=number. Also check with typeof if the variable is a number. If not, you can convert it with JavaScript function parseInt().
Please change the type of your inputs, then move your "validation" inside your loop, then
move your counter outside the loop and change it to "let", then cast to number the input value before sum into the current.
have a nice day
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="inp" type="number" placeholder="Enter a Number ">
<input class="inp" type="number" placeholder="Enter elec">
<input class="inp" type="number" placeholder="Enter food ">
<input class="inp" type="number" placeholder="Enter car ">
<input class="inp" type="number" placeholder="Enter resturent ">
<h1 class="total">total</h1>
<button class="btn">calculate</button>
<script>
let btn = document.querySelector('.btn')
btn.addEventListener('click', function () {
const total = document.querySelector('.total')
const inps = document.querySelectorAll('.inp')
let current = 0;
for (let i = 0; i < inps.length; i++) {
if (isNaN(inps[i].value)) {
alert("Not a number")
break;
} if (inps[i].value == "") {
alert("enter number ")
break;
}
current += +inps[i].value
total.innerHTML = current
}
})
</script>
</body>
</html>

How to make the calculate button work

I have this code that I'm working on, but the calculate button won't work no matter what I do. I want to find the cost per square inch using the pizzaSize and pizzaCost. How can I make the calculate button actually calculate?
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' >
<title> Pizza Calculator </title>
<script src="pizzaCalc.js">
</script>
</head>
<body>
<h1>Pizza Calculator</h1>
<p>
<label for="priceBox">Cost: </label><input type="text" id="priceBox" size="5"/></p>
<p>
<label for="sizeBox">Diameter :</label><input type="text" id="sizeBox"
size="5"/>
</p>
<input type="button" id="cpsi" value="Cost PSI" onclick="calculate(cpsi)">
</body>
</html>
"use strict"
function pizzaCalc () {
var size = document.getElementById ("sizeBox").value;
size = parseFloat (size);
var price = document.getElementById("priceBox").value;
price = parceFloat (price);
var costPerSquareInch = price / (3.14 * (size / 2)^2)
alert('Pizza value :' +costPerSquareInch);
document.getElementById("cpsi").value = costPerSquareInch;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' >
<title> Pizza Calculator </title>
<script src="pizzaCalc.js">
</script>
</head>
<body>
<h1>Pizza Calculator</h1>
<p>
<label for="priceBox">Cost: </label><input type="text" id="priceBox" value="5"/></p>
<p>
<label for="sizeBox">Diameter :</label><input type="text" id="sizeBox" value="5"/>
</p>
<input type="button" id="cpsi" value="Cost PSI" onclick="pizzaCalc()">
<script type="text/javascript">
"use strict"
function pizzaCalc () {
var size = document.getElementById ("sizeBox").value;
size = parseFloat (size);
var price = document.getElementById("priceBox").value;
price = parseFloat (price);
var costPerSquareInch = price / (3.14 * (size / 2)^2)
alert('Pizza value :' +costPerSquareInch);
document.getElementById("cpsi").value = costPerSquareInch;
}
</script>
</body>
</html>
It appears that
<input type="button" id="cpsi" value="Cost PSI" onclick="calculate(cpsi)">
should be
<input type="button" id="cpsi" value="Cost PSI" onclick="pizzaCalc()">
also I am assuming size should be value on the input tags.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' >
<title> Pizza Calculator </title>
<script src="pizzaCalc.js">
</script>
</head>
<body>
<h1>Pizza Calculator</h1>
<p>
<label for="priceBox">Cost: </label><input type="text" id="priceBox" value="5"/></p>
<p>
<label for="sizeBox">Diameter :</label><input type="text" id="sizeBox" value="5"/>
</p>
<input type="button" id="cpsi" value="Cost PSI" onclick="pizzaCalc()">
<script type="text/javascript">
"use strict"
function pizzaCalc () {
var size = document.getElementById ("sizeBox").value;
size = parseFloat (size);
var price = document.getElementById("priceBox").value;
price = parseFloat (price);
var costPerSquareInch = price / (3.14 * (size / 2)^2)
alert('Pizza value :' +costPerSquareInch);
document.getElementById("cpsi").value = costPerSquareInch;

.each not working to separate sections

I'm trying to create a number field (.item_adults) that multiply it self and print the value into a class="item_price". To do that I create some of this:
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="10" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">10</span></p>
</div>
$( document ).ready(function() {
$(".bookSection").each(function() {
$(".item_adults").change(function(){
var price = ($(this).val());
var ammount = ($(this).attr("data-price"));
var total = (price) * ammount;
$(".item_price").html(total);
});
});
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="10" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">10</span></p>
</div>
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="15" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">15</span></p>
</div>
</body>
</html>
and I'm using:
$(".bookSection").each(function() {
to try to separate it in sections to work independently modifying its own .item_price, but right now one section is affecting the other ones.
hope the explanation is clear, Thank you!
Look for the instances within each section using find()
$(".bookSection").each(function() {
var $item_price = $(this).find(".item_price")
$(this).find(".item_adults").change(function(){
var price = ($(this).val());
var ammount = ($(this).attr("data-price"));
var total = (price) * ammount;
$item_price.html(total);
});
});
Could also simplfy this without needing the each on the sections:
$(".item_adults").change(function(){
var price = ($(this).val());
var ammount = ($(this).attr("data-price"));
var total = (price) * ammount;
$(this).closest(".bookSection").find(".item_price").html(total);
});
Close, only a couple small changes. When you reference $(".item_adults") and $(".item_price"), it affects them all. Limit the scope to the CURRENT .bookSection, as below:
$( document ).ready(function() {
$(".bookSection").each(function() {
$(this).find(".item_adults").change(function(){
var price = ($(this).val());
var ammount = ($(this).attr("data-price"));
var total = (price) * ammount;
$(this).parents(".bookSection").find(".item_price").html(total);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="10" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">10</span></p>
</div>
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="15" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">15</span></p>
</div>
</body>
</html>

Can't figure out why this doesn't give me any output value

I'm extremely new to JavaScript and programming in general. Can someone explain to me why this doesn't work?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var months = document.getElementById('months').value;
var interest = (amount * (interest_rate * .01)) / months;
var payment = ((amount / months) + interest).toFixed(2);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Monthly Payment = $"+payment;
}
</script>
</head>
<body>
<p>Loan Amount: $<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Months: <input id="months" type="number" min="1" max="72" value="1" step="1" onchange="computeLoan()"></p
<h2 id="payment"></h2>
</body>
</html>
On Months - you're missing a bracket on your closing <p> tag. This is causing your <h2> to be undefined
<p>Months: <input id="months" type="number" min="1" max="72" value="1" step="1" onchange="computeLoan()"></p
the
</p
at the end is your problem.

Categories