JS how to use two arithmetic operators - javascript

i want to get data from input fields and do two arithmetic operations at same time (1)multiplication (2) addition. Multiplication is working but when i try to do 2nd operation i get some error. for example 2*2+2=6 but when i try the answer comes 42.
my code is here .
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a =$('#sfpm').val();
var b = $('#snom').val();
var c = $("#bonus").val();
var taamount = a*b+c ;
$('#staamount').val(taamount);
});
});
</script>

As you can see in this example the first box will cause multiplication, but the rest will concatenate ( simply append to ) the last digit present, which increases length but doesn't do any mathematical operation.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm">
snom<input id="snom">
bonus<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a =$('#sfpm').val();
var b = $('#snom').val();
var c = $("#bonus").val();
var taamount = a*b+c ;
$('#staamount').val(taamount);
});
});
</script>
This is because you're adding two strings together instead of numbers. Strings added together look like this:
let str = "Hello ", str2= "world!";
console.log(str + str2);
So it makes sense that they append. Numbers look like this:
console.log(1 + 5);
Which does what you expect, but the important thing to realize is that the + operator has multiple functions. it can either append or perform math. The difference as to what type of operation is performed is based solely on the type of the data you're using.
a string will append
a number will add
So in your code when you get the value using .val() - what's happening is that you're getting string values, not number values. To fix this we can do a few different things.
parseInt or Number methods will convert the values from .val() into integers:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm">
snom<input id="snom">
bonus<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a = parseInt($('#sfpm').val());
var b = Number($('#snom').val());
var c = parseInt($("#bonus").val());
var taamount = a*b+c ;
$('#staamount').val(taamount || 0);
});
});
</script>
One other way to coerce a string to a number is to simply place the + operator before the value. This will cause the interpreter to automatically try to change the value into a number.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sfpm<input id="sfpm"> snom
<input id="snom"> bonus
<input id="bonus">
<hr/>total<input id="staamount">
<script type="text/javascript">
$(document).ready(function() {
$('#sfpm,#snom,#bonus').keyup(function() {
var a = +$('#sfpm').val();
var b = +$('#snom').val();
var c = +$("#bonus").val();
var taamount = a * b + c;
$('#staamount').val(taamount || 0);
});
});
</script>

Use parseInt() to ensure you are getting the int version of the value, it looks like it is adding c as a string

You're trying to operate on string.
You're doing something '2' + '0' which will result as '20' not 2.
Because here + operator does the concatenation of two string not arithmetic addition
Change it number.
<script type="text/javascript">
$(document).ready(function(){
$('#sfpm,#snom,#bonus').keyup(function(){
var a =Number($('#sfpm').val());
var b = Number($('#snom').val());
var c = Number($("#bonus").val());
var taamount = a*b+c ;
$('#staamount').val(taamount);
});
});
</script>

Related

Calculating 2 values from fields but it's not working properly

I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));

Dynamic Regex for Decimal Precision not Working

I have the following hard-coded RegEx expression for decimal precision & scale, which works (in another project):
// This would be a Decimal(2,3)
var regex = /\d{0,2}(\.\d{1,3})?$/;
var result = regex.test(text);
However, I don't want to hard-code multiple variations. And, interestingly, the following fails...but I don't know why.
I "think" the concatenation may (somehow) be effecting the "test"
What am I doing wrong here?
SAMPLE:
var validationRules = {
decimal: {
hasPrecision: function (precision, scale, text) {
var regex = new RegExp('\d{0,' + precision + '}(\.\d{1,' + scale + '})?$');
var result = regex.test(text);
// result is ALWAYS true ????
alert(result);
alert(regex);
}
}
};
FAILING SAMPLE-SNIPPET:
$(document).ready(function () {
var validationRules = {
decimal: {
hasPrecision: function (precision, scale, text) {
var regex = new RegExp('\d{0,' + precision + '}(\.\d{1,' + scale + '})?$');
var result = regex.test(text);
alert(result);
alert(regex);
}
}
};
var masks = {
decimal: function (e) {
// TODO: get Kendo MaskedTextBox to run RegEx
var regex = new RegExp("^([0-9\.])$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
};
var button = $('.btn');
var textbox = $('.txt');
textbox.on('keypress', masks.decimal);
button.on('click', function () {
var text = textbox.val();
validationRules.decimal.hasPrecision(2, 3, text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="1111" class="txt">
<input type="button" class="btn" value="Run it">
Always look at the result when building dynamic strings. In your case you're building it and just assuming it's turning into the REGEX pattern you want.
What you're actually building is, for example:
d{0,2}(.d{1,3})?$
Why? Because REGEX patterns built via the constructor (as opposed to literals) are built as strings - and in strings \ is interpreted as an escape character.
You, however, need these back slashes to persist into your pattern, so you need to double escape. In effect, you need to escape the escape so the final one is retained.
var regex = new RegExp('\\d{0,' + precision + '}(\\.\\d{1,' + scale + '})?$');
This will result in an equivalent of your hard-coded pattern assuming precision and scale contain the intergers you think they do. Check this too. (If they contain floats, for example, this will ruin your pattern.)
As for your false positives, this is probably down to a missing start-anchor instruction, i.e. ^.
/\d{0,2}(\.\d{1,3})?$/.test("1234"); //true
/^\d{0,2}(\.\d{1,3})?$/.test("1234"); //false, note ^
please try this I have implement on my project and it's working fine
const integer = Number(4)
const decimal=Number(2)
const reg = new RegExp(^[0-9]{0,${integer }}(\\.\\d[0-9]{0,${decimal- 1}})?$)
return value && !reg.test(value) ? Maximum length for integer is ${integer} and for decimal is ${decimal} : undefined;

+$ in jquery. How come not only the basic $

I have some jQuery code where +$(...) is used in many places. The code does not work without the + part, when doing just $(...).
I couldn't find any explanation through Google. I'd appreciate any guidance if possible.
function calculate() {
var a = +$('#a').val(); // what is +$ ?
var b = +$('#b').val();
var c = b * 108.40;
//etc
}
+$() is actually two operations, where first $() runs to grab your input and then + coerces whatever the value of the input is into a number.
Here's a breakdown of what is happening:
var valueA = $('#a').val(); // "123"
var numberA = +valueA; // 123
console.log('valueA is a ' + typeof valueA); // 'valueA is a string'
console.log('numberA is a ' + typeof numberA); // 'numberA is a number'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="a" value="123"/>

get wrong result function jquery javascript

I am using the following script. But I am receiving a wrong result for x_b_bbetrag.
When do an calculation exp 100/108 I get 9.92 instead of 92.59.
What am I missing here?
Code below:
var betrag = 100
var kurs = 1
var minkl= 1
var msatz= 0.08
$("#x_b_betrag").change(function() {
var betrag = $("#x_b_betrag").val();
var kurs = $("#x_b_kurs").val();
var minkl =$("input[name='x_b_mwstinkl']:checked").val();
var msatz =$("input[name='x_b_mwst']:checked").val();
if (minkl == "1"){
$("#x_b_rechenbetrag").val((betrag * kurs).toFixed(2));
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + msatz) ).toFixed(2));
}
Use parseFloat
multiplication, division and subtraction automatically parse string to number. for summation you need to parse it.
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + parseFloat(msatz) ) ).toFixed(2));
///1 + "1" = 11 not 2
Parse your inputs into numbers.
For example :
var betrag = parseFloat($("#x_b_betrag").val());
MDN on parseFloat
The value of the msatz variable is not 0.08 but "0.08". It's a string, so when you add one to it, the number will be converted to a string so that they can be concatenated, and the result is "10.08" not 1.08. The string will implicitly be converted to a number when you use it in the division, as it's not possible to divide by a string.
Parse the string into a number:
var msatz = parseFloat($("input[name='x_b_mwst']:checked").val());

My VAT calculation is wrong

I'm trying to do a function for making a small calcul with vat.
So I have the following code:
<script type="text/javascript">
function calcdebours()
{
var taux = document.getElementById('debours_taux_tva').value;
var ht_no_tva = document.getElementById('debours_montant_ht_no_tva').value;
var ht_tva = document.getElementById('debours_montant_ht_tva').value;
var tva= Math.round((((ht_tva)*(taux))/100)*100)/100;
;
if(taux=='')
{
taux=0;
}
if(ht_no_tva=='')
{
ht_no_tva=0;
}
if(ht_tva=='')
{
ht_tva=0;
}
document.getElementById('debours_montant_tva').value = tva ;
document.getElementById('debours_montant_ttc').value = (tva) + parseInt(ht_tva)+ parseInt(ht_no_tva)
}
</script>
And below the fiddle:
http://jsfiddle.net/6zzRZ/
But for all it make the wrong calculation, I think it does not count the cent.
I've tried using just var 1 + var 2 but it just used to concatenate the number sor I use the parseInt function.
It has worked but the result is wrong for any kind of amount.
The trouble is that I tried parseDecimal but it say that this function does not exist.
Any kind of help will be much appreciated.
Try parseFloat. Or use the unitary + like this: var ht_no_tva = +document.getElementById('debours_montant_ht_no_tva').value; This gives JavaScript the hint that it should treat the value as a number.
Use parseFloat() instead of parseDouble:
http://www.w3schools.com/jsref/jsref_parsefloat.asp

Categories

Resources