I'm really new to JS. I am working on the if else statement and returning the total using the button. I also want to return some other input from HTML file also using the same button or on the same function as my calculate function. How do I return the total amount, name(input), number(input), from html to that one button as well?
If you don't get my question please run the code and see that it is not printing out the other input value. Thank you for helping me out.
function calculate() {
var total
var kwh = parseFloat(document.getElementById("kw").value);
if (kwh <= 50) {
total = (kwh * 500);
} else if (kwh <= 100) {
total = kwh * 1000;
} else {
total = kwh * 2120;
}
document.getElementById("total").innerHTML = total;
}
<body>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input id="name" type="text" placeholder="ឈ្មោះអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="លេខអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="kwh" id="kw">
</div>
<button type="button" onclick="calculate()">គណនា</button>
<p>Result: <span id="total"></span></p>
<p>Name: <span id="name"></span></p>
<!-- <script src="script2.js"></script> -->
</body>
You are very close just need a few tweaks.
You shouldn't repeat ids, so in that case, to make it easier to understand, we can rename the input with id name to name_input, so you can retrieve its value as
document.getElementById('name_input').value
You can add that to your function and assign it to the innerHTML of name inside the function calculate() and so on with as many actions as you want
Working snippet:
function calculate() {
var total
var kwh = parseFloat(document.getElementById("kw").value);
if (kwh <= 50) {
total = (kwh * 500);
} else if (kwh <= 100) {
total = kwh * 1000;
} else {
total = kwh * 2120;
}
document.getElementById("total").innerHTML = total;
document.getElementById("name").innerHTML = document.getElementById("name_input").value;
}
<body>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input id="name_input" type="text" placeholder="ឈ្មោះអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="លេខអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="kwh" id="kw">
</div>
<button type="button" onclick="calculate()">គណនា</button>
<p>Result: <span id="total"></span></p>
<p>Name: <span id="name"></span></p>
<!-- <script src="script2.js"></script> -->
</body>
Related
I have a product that cost 1,500.85 and i want to multiply it with the quantity input using javascript. But because the amount is over a thousand there is a comma and because of that comma the result shown "NaN" .. How do i calculate the amount with the comma?
NOTE: It works if the amount is under a thousand.
// Calculation script START
$(document).ready(function() {
CalculateTotalPrice();
});
document.getElementsByClassName("input-text qty text")[0].onkeyup = function() {CalculateTotalPrice()};
$(select).onchange(function() {
CalculateTotalPrice();
});
function CalculateTotalPrice() {
setTimeout(function(){
var price = document.querySelector(".price .woocommerce-Price-amount.amount").innerText;
var quantity = document.getElementsByClassName("input-text qty text")[0].value;
var total = price * quantity;
var totalOnly2Decimal = total.toFixed(2);
document.getElementById("result").innerHTML = "DKK " + totalOnly2Decimal + " inkl. moms";
}, 100);
}
// Calculation script END
<!-- Price -->
<div class="elementor-widget-container">
<p class="price">Fra:
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol"></span>1,122.50
</span> kr. inkl. moms</p>
</div>
<!-- Quantity field -->
<div class="quantity">
<label class="screen-reader-text" for="quantity_5cd3fab7bb0d7"></label>
<input type="number" id="quantity_5cd3fab7bb0d7" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Stk." size="4" inputmode="">
<!-- Result -->
<h3 style="font-size: 17px; font-weight:bold; display:inline; text-transform:uppercase;">Total:</h3>
<p class="result" id="result" style="display:inline;"></p>
Replace all the commas using String.prototype.replace then multiply.
let price = '1,500.85';
let quantity = '7';
let total = price.trim().replace(/,/g, '') * quantity;
console.log(total)
You can remove the comma with the replace method on the String object and convert to integer
price = parseInt(price.replace(/,/g,''))
var total = price * quantity;
Change this line to the following
var price =
document.querySelector(".price .woocommerce-Price-amount.amount").innerText.split(",").join("");
// Calculation script START
$(document).ready(function() {
CalculateTotalPrice();
});
document.getElementsByClassName("input-text qty text")[0].onkeyup = function() {
CalculateTotalPrice()
};
function CalculateTotalPrice() {
setTimeout(function() {
var price = document.querySelector(".price .woocommerce-Price-amount.amount").innerText.split(",").join("");
var quantity = document.getElementsByClassName("input-text qty text")[0].value;
var total = price * quantity;
var totalOnly2Decimal = total.toFixed(2);
document.getElementById("result").innerHTML = "DKK " + totalOnly2Decimal + " inkl. moms";
}, 100);
}
// Calculation script END
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Price -->
<div class="elementor-widget-container">
<p class="price">Fra:
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol"></span>1,122.50
</span> kr. inkl. moms</p>
</div>
<!-- Quantity field -->
<div class="quantity">
<label class="screen-reader-text" for="quantity_5cd3fab7bb0d7"></label>
<input type="number" id="quantity_5cd3fab7bb0d7" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Stk." size="4" inputmode="">
<!-- Result -->
<h3 style="font-size: 17px; font-weight:bold; display:inline; text-transform:uppercase;">Total:</h3>
<p class="result" id="result" style="display:inline;"></p>
<script>
</script>
There seemed to be a couple of errors with your snippet that i've done my best to fixup below. To answer your question, there are two main points:
var priceAsFloat = parseFloat(price.replace(/,/g, ''));
Remove the comma from the price and then convert it to a float before doing any maths with it
var result = totalOnly2Decimal.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
Convert the result back to a string and use the above regex to put commas back in at the desired points.
Working example:
// Calculation script START
$(document).ready(function() {
CalculateTotalPrice();
});
document.getElementsByClassName("input-text qty text")[0].onkeyup = function() {CalculateTotalPrice()};
$("input").change(function() {
CalculateTotalPrice();
});
function CalculateTotalPrice() {
setTimeout(function(){
var price = document.querySelector(".price .woocommerce-Price-amount.amount").innerText;
var priceWithoutCommas = price.replace(/,/g, '');
var quantity = document.getElementsByClassName("input-text qty text")[0].value;
var total = priceWithoutCommas * quantity;
var totalOnly2Decimal = total.toFixed(2);
var result = totalOnly2Decimal.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
document.getElementById("result").innerHTML = "DKK " + result + " inkl. moms";
}, 100);
}
// Calculation script END
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Price -->
<div class="elementor-widget-container">
<p class="price">Fra:
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol"></span>1,122.50
</span> kr. inkl. moms</p>
</div>
<!-- Quantity field -->
<div class="quantity">
<label class="screen-reader-text" for="quantity_5cd3fab7bb0d7"></label>
<input type="number" id="quantity_5cd3fab7bb0d7" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Stk." size="4" inputmode="">
<!-- Result -->
<h3 style="font-size: 17px; font-weight:bold; display:inline; text-transform:uppercase;">Total:</h3>
<p class="result" id="result" style="display:inline;"></p>
I'm working on a tax calculator using HTML and Javascript. It needs to accept two user inputs ("Total owed" and "Your payment") and calculate what percentage "Your payment" is of "Total owed". Then they should be displayed within the "answerParagraph" tag. What is the best way to do this?
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text">
</div>
<button onclick="handlers.getPercentage()">Get percentage</button>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
var taxes = {
getPercentage: function(total, payment) {
var percentage = (Math.floor((payment / total) * 100));
},
}
var handlers = {
getPercentage: function() {
var totalInput = document.getElementById('totalInput');
var paymentInput = document.getElementById('paymentInput');
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
}
}
</script>
</body>
</html>
You have to return the answer from taxes.getPercentage function
getPercentage: function (total, payment) {
var percentage = (Math.floor((payment / total) * 100));
return percentage;
}
And display in your answerParagraph. So, in handlers.getPercentage :
...
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
answerParagraph.innerHTML = answer;
the following modified code should work
var taxes = {
getPercentage: function(total, payment) {
var percentage = (Math.floor((payment / total) * 100));
return percentage
},
}
var handlers = {
getPercentage: function() {
var totalInput = document.getElementById('totalInput');
var paymentInput = document.getElementById('paymentInput');
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
document.getElementById('answerParagraph').innerHTML = answer
}
}
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text">
</div>
<button onclick="handlers.getPercentage()">Get percentage</button>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
</script>
</body>
</html>
You can leave out the button if you trigger the calcpercentage() function by the keyup-event on either of the two input fields:
// define shorthand notation byId(id):
const byId=id=>document.getElementById(id);
// delegated event binding: affects INPUT elements only
byId('getPercentage').addEventListener('keyup',function(ev){
if(ev.target.tagName!='INPUT') return false;
byId('answerParagraph').innerHTML=
(byId('paymentInput').value*100 /
byId('totalInput').value).toFixed(2)+"%";
});
// trigger event manually ...
byId('totalInput').dispatchEvent(new Event('keyup',{bubbles:true}));
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text" value="1000">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text" value="25">
</div>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
</script>
</body>
</html>
I want to get a number from a form-control type = "number", compare it, and then if OK with the condition, perform multiplication, and division on it. After that I want to display the result as the contents of a <p> tag. How to accomplish this?
Here is what I have tried so far:
let amount = document.getElementById(".amount");
let marginAmount = document.getElementById(".marginAmount")
let submit = document.getElementById(".submit");
submit.addEventListener('click', calcAmount);
const calcLevel1 = amount * 7 / 100;
function calcAmount() {
let userAmount = Number(amount.value);
let level1 = 351;
if (userAmount <= level1) {
marginAmount.textContent = calcLevel1.value;
}
}
<div class="form">
<label for="points amount">Entrez un montant en points</label>
<input type="number" class="amount-enter" id="amount">
<input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter">
</div>
<p id="marginAmount" class="enter-margin"></p>
Here is the code corrected, there are. Which are to be deleted
I also added math.round to get rounded result:
<html>
<head>
<script>
function calcAmount() {
let userAmount = document.getElementById("amount").value;
let level1 = 351;
if (userAmount <= level1) {
document.getElementById("marginAmount").textContent = Math.round(userAmount * 7) / 100;
} else {
document.getElementById("marginAmount").textContent = "Amount is > 351";
}
}
</script>
</head>
<body>
<div class="form">
<label for="points amount">Entrez un montant en points</label>
<input type="number" class="amount-enter" id="amount">
<input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter" onclick="calcAmount()">
</div>
<p id="marginAmount" class="enter-margin"></p>
</body>
Three things:
You had . in your ID selectors, these shouldn't be there (they should be # but only in a querySelector method).
You were calculating calcLevel1 straightaway, which meant it was 0 * 7 / 100 which is 0.
You needed to calculate calcLevel1 with amount.value, which means you can remove calcLevel1.value when you're setting the textContent of the paragraph.
I also added an else statement so the textContent is emptied when the statement is false.
let amount = document.getElementById("amount");
let marginAmount = document.getElementById("marginAmount")
let submit = document.getElementById("submit");
submit.addEventListener('click', calcAmount);
function calcAmount() {
const calcLevel1 = amount.value * 7 / 100;
let userAmount = Number(amount.value);
let level1 = 351;
if (userAmount <= level1) {
marginAmount.textContent = calcLevel1;
} else {
marginAmount.textConten = "";
}
}
<div class="form">
<label for="points amount">Entrez un montant en points</label>
<input type="number" class="amount-enter" id="amount">
<input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter">
</div>
<p id="marginAmount" class="enter-margin"></p>
I am working on a project where I have to add a database value to in input value.
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
</div>
In above code 680 will come from the database. Here I want to add an input number to that 680. I am very new to jQuery.
My JavaScript code is
$(document).ready(function() {
var total = 0;
$("input").keyup(function(){
var priceList = $('.price');
$.each(priceList, function(i, price){
total += parseFloat($(price).text());
});
alert(total);
});
});
</script>
In this it outputs "NaN".
In this it outputs "NaN".
You get this message since you're trying to loop through div's and parsing the text of them, when it's empty. You need to loop over input's instead.
You could init the total with the database value then loop through the input's and add the parsed values to total in every iteration.
NOTE: Use input event instead when you track the user input since it's more efficient.
Multiple inputs:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
$('.price input').each(function() {
total += parseFloat($(this).val()) || 0;
});
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Single input:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
total += parseFloat($(this).val()) || 0;
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Here you go
var result = 0;
var price = +$('#price').text();
$('input[type="number"]').on('input', function() {
var val = +$(this).val();
result = parseInt(val + price);
$('#price').text(result)
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price" id="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
I have a form I am trying to do, where if some one inputs text in a text field of a form, then clicks submit, I want to show him the cost of the sign (charactercount x price) i keep getting NaN!
Heres my Html:
<section class="sign" id="sign">
<h3 class="sign_header">CUSTOM SIGNAGE</h3>
<p class="sign_text">Enter Name, the cost per letter is $<span id="lettercost">6</span>.</p>
<form class="info_form">
<input type="text" id="inputletters" value="Example Name"><br>
<input type="button" value="Submit" class="button" id="getprice" onClick="getPrice();">
</form>
and here is my Javascript
function getPrice(){
var quantity = document.getElementById('inputletters').value.length;
var price = document.getElementById('lettercost');
var total = quantity*price;
var cost = document.getElementById('cost');
cost.textContent = total;
}
Here's a runnable example -- price was an object, you want .textContent, and parse those into numbers for this to work.
function getPrice() {
var quantity = document.getElementById('inputletters').value.length;
var price = document.getElementById('lettercost').textContent;
console.log(typeof quantity, typeof price)
var total = Number(quantity) * Number(price);
var cost = document.getElementById('cost');
cost.textContent = total;
}
<section class="sign" id="sign">
<h3 class="sign_header">CUSTOM SIGNAGE</h3>
<p class="sign_text">Enter Name, the cost per letter is $<span id="lettercost">6</span>.</p>
<form class="info_form">
<input type="text" id="inputletters" value="Example Name"><br>
<input type="button" value="Submit" class="button" id="getprice" onClick="getPrice();">
</form>
<div id="cost"></div>
</section>