Tip Calculator not giving Total Amount - javascript

I'm trying to create a tip calculator but I'm having trouble creating a variable that will give me the total amount of the bill. Below is the code, any suggestions?
function tipCalculate (slider, bill){
var tip = document.getElementById('tipamount');
var slideval = document.getElementById('slideval');
var bill = document.getElementById(bill).value;
var prcnt = slider * .01;
var total = Number(bill) + tip;
if (bill == null || bill == '') {
tip.innerHTML = 'Please enter an amount';
return false;
}
if(isNaN(bill)) {
tip.innerHTML = 'Please enter a number';
return false;
}
if(bill >= 0){
tip.innerHTML = '$' + (bill * prcnt) .toFixed(2);
slideval.innerHTML = slider + '%';
}
}

Line 6 is your problem. tip is a dom element and you are trying to add it to a value accessed in the dom i.e bill's value;
This line is not correct:
var total = Number(bill) + tip;

Related

Wrong output when using a function

I have a function that calculates the price something.
When the age < 5 then price = 0,
when the age < 15 the price = price/2
and when age > 15 the price = price + price*0.15. The first 2 are working fine but the last one has a problem. When for example a put 100 on the price input and 26 on the age input the answer that it gives me is 10015.
<script>
function add(x, y) {
return x+y;
}
function Subtract(x, y) {
return x-y;
}
function Divide(x, y) {
return x/y;
}
function Multiply(x, y) {
return x*y;
}
var plusPrice = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
var plusButton = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function updateClickCount() {
document.getElementById("clicks").innerHTML = plusButton();
if (document.getElementById("price").value !== '') {
document.getElementById("input").innerHTML = plusPrice();
}
}
function checkInputs() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if( parseInt(price) < 0 || isNaN(parseInt(price))) {
window.alert("Please insert a valid price");
price = '';
}
if(parseInt(age) > 100 || parseInt(age) < 0 || isNaN(parseInt(age))){
window.alert("Please insert a valid age");
age = '';
}
}
function Calculate() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if (document.getElementById("price").value !== '' && document.getElementById("age").value !== '') {
if (age<5) {
document.getElementById("demo").innerHTML = Subtract(price,price);
} else if (age < 15 && age >= 5) {
document.getElementById("demo").innerHTML = Divide(price,2);
} else {
document.getElementById("demo").innerHTML = add(price,Multiply(price,0.15));
}
} else {
window.alert("Please fill both age and price to calculate the amount you have to pay");
}
}
</script>
<body>
Please enter the price: <br>
<input type="text" id="price"><button onclick="document.getElementById('price').value = ''">Clear input field</button><br><br>
Please enter your age: <br>
<input type="text" id="age"><button onclick="document.getElementById('age').value = ''">Clear input field</button><br><br>
<button onclick="checkInputs(); updateClickCount(); Calculate();">Calculate price</button>
<p id="totalPrice">The total amount you have to pay is: </p><br>
<p id="demo"></p>
<p>Button Clicks: <a id="clicks">0</a></p>
<p>Correct Price Fill Count: <span id="input">0</span></p>
</body>
Apparently, price is a string. Replace
var price = document.getElementById("price").value;
with
var price = parseFloat(document.getElementById("price").value);
The function has already worked for subtraction and division, because operators - and / can't be applied to strings, so JS coerces them to numbers. The +, however, has a string-compatible interpretation (string concatenation), so type coercion doesn't happen.
or do this
var price = Number(document.getElementById("price").value);
In JavaScript the + symbol can be used both for numeric addition and string concatenation, depending on the variables either side. For example,
console.log('value:' + 4); // 'value:4'
console.log(3 + 1); // 4
console.log('value:' + 4 + '+' + 1); // 'value:4+1'
console.log('value:' + 4 + 1); // 'value:41'
console.log('value:' + (3 + 1)); // 'value:4'
console.log(4 + ' is the value'); // '4 is the value
Hence convert your operands to numeric type before proceeding with addition so that they are not concatenated.
Hope this clarifies.

How can I output an error message in my currency converter if the user inputs wrong value?

I was wondering how I could output an error message telling the user to enter a whole number or a decimal number if they input a special symbol such as "#" or a character letter into the amount of my currency converter program.
Codepen
JAVASCRIPT
// Fetch exchange rate data from api
$.getJSON("https://api.fixer.io/latest?base=ZAR", function(data) {
var currencies = [];
$.each(data.rates, function(currency, rate) {
// Currency options dropdown menu
currencies.push("<option id='" + currency.toLowerCase() + "' value='" + rate + "' >" + currency + "</option>");
});
$(".currency-list").append(currencies);
})
//Calculate and output the new amount
function exchangeCurrency() {
var amount = $(".amount").val();
var rateFrom = $(".currency-list")[0].value;
var rateTo = $(".currency-list")[1].value;
if (amount == undefined || rateFrom == "--Select--" || rateTo == "--Select--") {
$(".results").html("0");
} else {
$(".results").html((amount * (rateTo * (1 / rateFrom))).toFixed(2));
}
}
You can check if the number is valid (before other checks) using one of many JS methods (regex, isNaN etc) and then show or hide some error element accordingly. Number verify methods vary when it comes to some edge/specific cases, but using "number" field alone will prevent most of the bad inputs:
pen
//Calculate and output the new amount
function exchangeCurrency() {
var amount = $(".amount").val();
var rateFrom = $(".currency-list")[0].value;
var rateTo = $(".currency-list")[1].value;
if ((amount - 0) != amount || (''+amount).trim().length == 0) {
$(".results").html("0");
$(".error").show()
} else {
$(".error").hide()
if (amount == undefined || rateFrom == "--Select--" || rateTo == "--Select--") {
$(".results").html("0");
} else {
$(".results").html((amount * (rateTo * (1 / rateFrom))).toFixed(2));
}
}
}

code stops looping

My code is not working properly. It is not continuing the loop. It is just showing that your value is low or high and stopping it there. Why doesn't it keep looping?
var target;
var count = 0;
var play;
var game;
function do_this() {
var choose = (Math.floor(Math.random() * 100));
target = choose + 1;
while (true) {
play = prompt("I am thinking of a no. between 1 and 100\n\n" + "enter the no.");
game = parseInt(play);
count = count + 1;
if (isNaN(game)) {
alert("Please enter integer value");
return false;
}
if ((game < 1) || (game > 100)) {
alert("Please enter the value between 1 and 100");
return false;
}
if (game < choose) {
alert("enter higher value");
return false;
}
if (game > choose) {
alert("enter lower value");
return false;
}
alert("You are correct\n\n" + "you took" + count + "to guess the game");
return true;
}
}
do_this()
You are using return false; when the value is higher or lower. Replace that with continue;

Contribution margin percentage

I have made a formula to calculate contribution margin of a product, the thing is that the percentage is limited to 100%.
If we buy a product for 0.2€ and sell it for 99€, basically we earn more then 100% of the value.
$("#tb_calculator").change(function(){
$this = $(this);
var price_in = $this.find(".tb_price_in").val().replace(',', '.');
var price_out = $this.find(".tb_price_out").val().replace(',', '.');
var quantity = $this.find(".tb_quantity").val().replace(',', '.');
//var percentage = (price_out / price_in - 1)*100;
var percentage = (price_in / price_out);
var tb_value = (price_out*quantity - price_in*quantity);
//console.log(percentage);
var final_percentage = Math.round(((1-percentage)*100));
if (final_percentage === Infinity || final_percentage === "" || isNaN(final_percentage) || final_percentage < 0 || percentage < 0) {
var final_percentage = 0;
}
if (tb_value === Infinity || tb_value === "" || isNaN(tb_value)) {
var tb_value = 0;
}
function tofixed(val)
{
return parseFloat(val.toFixed(2));
}
$(".tb_count").val(tofixed(tb_value)+"kr - ("+final_percentage+"%)");
});
jsFiddle

more than currency input field

I have this input tag where you put the total of your receipt :
<input type="text" name="currency" id="currency" class="text-input" onBlur="this.value=formatCurrency(this.value);" />
The Javascript is as follows:
<script type="text/javascript">
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) {
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num % 100;
num = Math.floor(num/100).toString();
if(cents < 10) {
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
</script>
Users can only enter receipts more than $10.00 bucks, how can I set that on my script? Also they need to know they can not enter currency less than $10.
From what I can gather from your question I think you are looking for something like this. Basically if we have a valid entry such as $100.00 we continue, return true etc, else if we have something that looks like an int or float we can reformat this and recurse the function, else hint user for of vaild entry
var foo = document.getElementById('foo');
foo.addEventListener('blur', function(e) {
var val = e.target.value;
var err = document.getElementById('err');
var errMsg = 'please enter a value $10.00 or greater';
var patt = /^\$\d+\.\d{2}$/;
var amount = parseInt(val.replace(/\$|\./g, ''));
if (val !== '') {
if (patt.test(val)) {
if (amount < 1000) {
err.textContent = errMsg;
} else {
document.getElementById('suc')
.textContent = 'processing request';
}
} else if (typeof amount == 'number' && !/[a-z]/g.test(val)) {
if (/\.\d{2}/.test(val)) {
e.target.value = '$' + (amount / 100);
} else {
e.target.value = '$' + amount + '.00';
}
arguments.callee(e);
} else {
err.textContent = errMsg;
}
}
});
here is a demo
You can apply a validation function when submitting the form to test if the value is below a threshold, such as:
function validate()
{
value = document.getElementById('currency');
if (value <= 10.00)
{
return false
} else
{
return true;
}
}
You could also apply this to the onblur event, but my preference is to present validation errors when the form is submitted.
It looks like you're trying to parse a string, convert it nicely into dollars and cents, and reject it if it's less than 10. There's a much nicer way to do that:
function formatCurrency(num) {
// Remove the dollar sign
num = num.replace("$", "");
// Change the string to a float, and limit to 2 decimal places
num = parseFloat(num);
Math.round(num * 100) / 100;
// If its less than 10, reject it
if(num < 10) {
alert("Too small!");
return false;
}
// Return a nice string
return "$" + num;
}
At the end, are you trying to return -$99.94 if the number is negative?

Categories

Resources