I am working on fixing a website which is coded by someone else. Codes are really messy so I am afraid I can't post it all here but I believe I provided enough information for you to see what could be wrong. Because at this point I am lost.
1. We get min and max limits
parent_id = '<?php echo $parent_id; ?>';
api = '<?php echo $api; ?>';
$.getJSON('getlimits.php', {'id': ""+parent_id+"", 'api': ""+api+""}, function(data) {
// Loop and assign Json (returned value) to our limit variables
$.each(data, function(key, val) {
min_limit = key;
max_limit = val;
});
});
getlimits.php OutPut:
{"10":"15000"}
2. We check the limits
amount = $('#quantity', this).val();
console.log(amount + ' - Max : ' + max_limit + ' Min : ' + min_limit);
if ( amount < min_limit) {
displayError("You can't order less than " + min_limit + " units",2000);
return false;
}
else if ( amount > max_limit ) {
displayError("You can't order more than " + max_limit + " units.",2000);
return false;
}
Logged Results;
800 - Max : 15000 Min : 10
I typed 800 units. It shouldn't give any error but I am getting following error;
You can't order more than 15000 units.
I am truly lost. Log shows correct values, getlimits.php returns correct values but if & else if conditions are not working.
I will be glad if anyone could help me out with this problem.
Thank you in advance.
amount is not an integer when you grab it through .val().
So adjust this line:
amount = $('#quantity', this).val();
to
amount = parseInt($('#quantity', this).val());
As pointed out by Dennis, you will have to parseInt the values you are grabbing from the JSON as well. (min_limit and max_limit).
As Dennis also pointed out, you should add 10 as a second parameter to parseInt to make sure it parses as a decimal number.
So:
$.each(data, function(key, val) {
min_limit = parseInt(key,10);
max_limit = parseInt(val,10);
});
amount = parseInt($('#quantity', this).val(),10);
It's because you are comparing a string to string:
"800" > "15000" === true
You need to convert at least one (preferably both) to a number with parseInt:
$.each(data, function(key, val) {
min_limit = parseInt(key);
max_limit = parseInt(val);
});
amount = parseInt($('#quantity', this).val());
Make sure you call parseInt(number, 10) to get a numeric variable. It looks like you are comparing strings which will give you different results from comparing numbers. The second parameter (10) is the radix, which will make sure you get a decimal value.
You need to do this for min_limit and max_limit, as well as the .val() call, which will always return a string.
Related
I am having an issue with a Nan error in my typescript. I have set a variable type to number and loop throuh an element where I get all the different balance amounts. They come in the form of "$..." like $10.00 and $20.00, so I do a replace and then finally include each balance amount into the total sum balance variable.
However, in my console log it outputs:
Expected: NaN
Actual: 20.00
I am not sure why that is. Why does it think it's not a number and how can this be rectified (should show 20.00)
balance: Selector;
this.balance = Selector('.balance');
this.balanceTotal = Selector('.balance-total ');
async validateTotalBalance() {
let sumBalanceTotal: number = 0;
for (let i = 0; i < (await this.balance.count); i++) {
let amount = await this.balance.nth(i).textContent;
amount.replace('$', '');
let convertedAmount = Number(amount);
convertedAmount.toFixed(2);
sumBalanceTotal += convertedAmount;
}
console.log('Expected: ' + sumBalanceTotal);
console.log(
'Actual: ' + (await this.balanceTotal.textContent).replace('$', '')
);
}
amount.replace('$', '');
This line is not storing the result of the replace so amount still has $ in it after, which could be why the value is NaN
This is because toFixed() returns a string. Use toFixed() until calculations are done or only before you need to present the data.
I have a value separated by commas. The code is as follows:
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g, ''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
var pay = document.getElementById("values").value;
payment = pay.replace(/\,/g, '');
<label>Rent</label> <input style="font-size:10px;width:80px;text-align:right" id="values" type="text" onkeyup="addComma(this);">
Issue:
if (selectedPayType === "A") {
PV = getNPV(rate, array, payment) + payment;
console.log("PV);
}
For some reason, PV returns the value but it doesn't add the +payment. But, instead of +payment, if i use the numeric value itself ex: 10000, then it adds the value up.
I tried debugging and it is taking the payment value inside the getNPV however, not adding it up which is really weird. Not sure what i am doing wrong here. Any help is appreciated. Thank you.
The main problem is that you are adding a string to a number . For eg: 1 + '2' = '12'. So you need to convert your payment which is a string, into a number.
Do not use Number constructor as it might cause unwanted results, but use parseFloat or parseInt to convert numeral strings into numbers.
p.s. for parseInt you should/need to specify a radix .
Useful links
parseInt()
parseFloat()
why avoid creating object versions of primitives
Changed a bit the structure ( added the if inside the addComma function that is called onkeyup )
See below
function addComma(values) {
const v = values.value && parseFloat(values.value.replace(/,/g, ''));
values.value = v.toLocaleString();
if (document.getElementById("values")) {
var pay = document.getElementById("values").value;
payment = pay.replace(/\,/g, '');
PV = 10 + parseFloat(payment);
console.log(PV);
}
}
<label>Rent</label> <input style="font-size:10px;width:80px;text-align:right" id="values" type="text" onkeyup="addComma(this);">
In my code, I have this:
<script language="javascript">
function addNumbers()
{
var collect = parseFloat(document.getElementById("Collect").value);
var current = parseFloat(document.getElementById("Current").value);
var Balance = document.getElementById("Bal");
Balance.value = collect + current;
}
</script>
If, for example,the input is: 123.12 + 12.22, the Balance is 135.34
But if the input is : 123.00 + 12.00, the Balance is 135 instead of 135.00.
What should I add to achieve the 2nd output sample?
Thanks.
Use ToFixed(2) mdn
(123.00 + 12.00).toFixed(2) //135.00
Also , use || operator.
So :
function addNumbers()
{
var collect = parseFloat(document.getElementById("Collect").value) ||0;
var current = parseFloat(document.getElementById("Current").value) ||0;
var Balance = document.getElementById("Bal");
Balance.value = (collect + current).toFixed(2);
}
Small gotcha :
(9.999 +9.999).toFixed(2) //"20.00"
So how would I solve it ?
simply :
Multiply by 1000 each and then move decimal point.
It sounds like parseFloat() is working correctly but it's the output that isn't quite to your liking. Try using Number's .toFixed() function for formatting:
Balance.value = (collect + current).toFixed(2)
There's some great discussions of formatting currency over on this question: How can I format numbers as money in JavaScript?
I have an issue in doing a simple addition and save the value in a variable.
Basically I have the following code:
var accsen;
var lowsev = parseInt(accsen);
var hisev = parseInt(accsen) + parseInt(0.65);
console.log('Lowsev: ' + lowsev);
console.log('Hisev: ' + hisev + ' Type: ' + typeof(hisev));
console.log('Accsen: ' + accsen);
The variable accsen is being given a value from the database. Lowsev is being assigned the same value as accsen,while hisev is being assigned the value of accsen + 0.65.
However the issue I am having is that both lowsev and hisev are remaining 0. On doing console.log I get these values:
Lowsev: 0
Hisev: 0 Type: undefined
Accsen: 0.75
Can anyone tell me what I am doing wrong in the addition? Am I using the correct operators?
Sounds like you want to use parseFloat instead of parseInt.
"Lowsev is being assigned the same value as accsen" It's not, you're rounding it to an integer.
But parseInt() doesn't round properly. 0.75 comes out as 0, so it's working. Assuming you actually want to round these values try
var accsen;
var lowsev = Math.round(accsen);
var hisev = Math.round(accsen) + Math.round(0.65);
EDIT given the response
Your JS is treating accsen as a string, you need to convert to a number
var accsen = '0.75'; // as other people have noted this val in your code is missing.
var lowsev = parseFloat(accsen);
var hisev = parseFloat(accsen) + 0.65;
I have 1 select, 2 text inputs & some JSON data in a form:
select input: List of Suppliers
text input 1: Net Amount
text input 2: Gross Amount
JSON Data:contains the rates of various suppliers as JSON in supplier_tax_rates
I am calculating Gross Amount something like this(pseudo code):
grossAmount = NetAmount + ((currently_selected_supplier.tax_percentage_charged / 100) * netAmount)
Here is the complete code:
Calculate total after retriveing tax rate from JSON
Now, this should work but it doesn't. I get NaN(not a number), means something is wrong. But I have trouble find where.
JSfiddle
You have multiple problems in your code. Here is the correct version:
var taxRates = $.parseJSON(supplier_tax_rates);
var getTaxRate = function(id) {
for (var i in taxRates) { // correct loop definition
if (taxRates[i].id == id) { // check you get id correctly
return taxRates[i].tax_percentage_charged; // instead of 'rate'
}
}
};
$('#PurchaseNetAmount').on('change', function(event) {
var taxRatesId = $('#PurchaseSupplierId').val();
var netAmount = parseFloat(this.value);
var grossAmount = netAmount + ((getTaxRate(taxRatesId) / 100) * netAmount);
$('#PurchaseGrossAmount').val(grossAmount);
});
DEMO: http://jsfiddle.net/A9vmg/18/
Your problem is in the look up function.
for(TaxRate in supplier_tax_rates ){
supplier_tax_rates is a string, not a JSON object
Than after you fix that you will have another error
return rate;
What is rate?
Learn to use console.log() or breakpoints so you can step throught your code and debug it.
getTaxRate(taxRatesId) return undefined