Adding together values of jQuery.html()? - javascript

How would I add together the values pulled from two separate jQuery.html() calls? Example:
<div id="a">27</div>
<div id="b">3</div>
$(document).ready(function(){
var a = $("#a").html();
var b = $("#b").html();
var c = a + b;
});
All the above does is concatenate var a and b into c (i.e. c = 273) because a & b are strings. How do I get the actual values so that I can properly add them?

You can do either
var a = +$("#a").html();
or
var a = parseInt($("#a").html(), 10);
both of which cast the string to an integer. For more info, see How do I convert a string into an integer in JavaScript?.

Use the parseInt() function:
$(document).ready(function(){
var a = parseInt($("#a").html(), 10);
var b = parseInt($("#b").html(), 10);
var c = a + b;
});

You can use + in both operands
var c = +a + +b;

use text() instead of html().
var x = parseInt( $(el).text(), 10 );

Related

After Addition two variables in javascript returning some garbage values

Hi I have two variables in JS Like:
var a = 223620.42
var b = 1200.1234
I am using Calculation Like:
var c = parseFloat(a) + parseFloat(b);
So the result should be = 224820.5434
But it returning 224820.54340000002
Please Suggest me what I am doing wrong here. Thanks in advance
Just Round-off the last Values. See the Code Below:
var a = 223620.42
var b = 1200.1234
var c = parseFloat(a) + parseFloat(b);
var numb = c.toFixed(4);
alert(numb);
hope it will solve you problem.
Try Using "toPrecision" method, and specify the desired length of the number.
var a = 223620.42
var b = 1200.1234
var c = parseFloat(a) + parseFloat(b);
c= c.toPrecision(3)

How to split math calculations in javascript

I have mathematical calculations in div tag, like that:
13*7=91
So how to split and parse data?
and it will stored in variables like that:
var A = 13;
var Operation = '*';
var B = 7;
var Result = 91;
please tell me how to make that :)
You can split it first by = sign, and then by possible math signs, for example:
var s = '13*7=91';
var a = s.split('=');
var b = a[0].split(/[\+\-\*\/\^%]/);
var A = b[0];
var B = b[1];
var Operation = a[0].replace(A,'').replace(B,'');
var Result = a[1];
console.log(A+Operation+B+'='+Result);
Output:
13*7=91
This is an easy way of doing it, simply using RegExp.
The first one is /[0-9]+/g to take the operands and the result numbers and the second one is /[0-9]+(.)[0-9]+/ to extract the operator, then I print the result in a diplay p elemnt:
var str = document.getElementById("calcul").innerText;
var re = /[0-9]+/g;
var re2 = /[0-9]+(.)[0-9]+/;
var operands = str.match(re);
var operator = str.match(re2)[1];
var A = operands[0];
var B = operands[1];
var result = operands[2];
var display = document.getElementById("display");
display.innerHTML = "var A = " + operands[0] + "<br>var B = " + operands[1] + "<br>var result = A" + operator + "B =" + result;
<div id="calcul">
13*7=91
</div>
<br>Calculation results :
<p id="display">
</p>
Maybe you can try something like this:
Make a regular expression that detects the numbers separated by anything (+, *, -, /, =, etc).
Make that regular expression detects the separating elements.
Then execute eval() in javascript. Be careful with this.
When you have a piece of code show us and we can help you better.
Good luck.

JavaScript Addition Operators not work

I try using javascript but the addition is not correct, live code here
function hitung2() {
var a = $(".a2").val();
var b = $(".b2").val();
c = a * b; //a kali b
d = c + a;
$(".c2").val(c);
$(".d2").val(d);
}
function hitung2() {
var a = parseInt($(".a2").val());
var b = parseInt($(".b2").val());
c = a * b; //a kali b
d = c + a;
$(".c2").val(c);
$(".d2").val(d);
}
Or if you going to work with fractions then use parseFloat() function in same way as it described above.
You need to change the string that you get from .val to ints with parseInt()
var a = parseInt($(".a2").val());
var b = parseInt($(".b2").val());
Updated fiddle. http://jsfiddle.net/b39Lz/32/
use parseInt()
var a = $(".a2").val();
var b = $(".b2").val();
temp1=parseInt(a);
temp2=parseInt(b);
c = temp1 * temp2;
d = c + temp1;
Your variables are String, so it uses String + operator, does concatenating the value. Convert string to int using: parseInt("10")
function hitung2() {
var a = $(".a2").val();
var b = $(".b2").val();
c = a * b; //a kali b
d = parseInt(c) + parseInt(a);
$(".c2").val(c);
$(".d2").val(d);
}
Avoid using parseInt() if you dont want to stick to integer calculations only.Try casting to general Number.
function hitung2() {
var a =Number( $(".a2").val());
var b = Number($(".b2").val());
var c = a * b; //a kali b
d =Number(c)+Number(a);
$(".c2").val(c);
$(".d2").val(d);
}

Manipulate replace string in javascript

I have three variables in javascript like
var a = document.getElementById("txtOrderNumberRelease1").value;
var b = document.getElementById("txtOrderNumberRelease2").value
var c = document.getElementById("ddlOrderNumberRelease3");
and
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY"
In mainString, the value "789" is coming from variable "a",
value "456" is coming from variable b and value "LLX" is coming from variable "c".
Variables "a" and "b" will always be Integers, whereas variable "c" will always be one the three values ie. "LLI,LLA,LLX".
Before value "789", there can be any number of words splitted by hypen "-". like ROAM-LCD-Synergy-SSI etc...
But after the value of variable "c" i.e "LLX" in mainString, there can be only one word for eg. "WARRANTY".
Now my issue is, I have to replace these three values of "a","b" and "c" ie. "789-456-LLX" with my newly entered values lets say 987-654-LLA, then my desired final string would be
old string: mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY"
desired string: mainString ="ROAM-LCD-Synergy-987-654-LLA WARRANTY"
Please suggest some wayout.
Thanks
var a = 123;
var b = 456;
var c = "ABC";
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY";
var updatedString = mainString .replace(/\d{3}-\d{3}-[A-Z]{3}\s([^\s]*)$/,a+"-"+b+"-"+c+" $1");
console.log(updatedString);
Something like this should work:
mainString.replace(/[\d]{3}\-[\d]{3}\-[\w]{3}\s([\w]+)$/, a + "-" + b + "-" + c + " $1");
Here's an option that uses string.split.
function replaceLastThreeDashedFields(original,a,b,c) {
var spaceSplit = original.split(' ');
var dashSplit = spaceSplit[0].split('-');
dashSplit[dashSplit.length - 3] = a;
dashSplit[dashSplit.length - 2] = b;
dashSplit[dashSplit.length - 1] = c;
var newDashed = dashSplit.join('-');
spaceSplit[0] = newDashed;
var newSpaced = spaceSplit.join(' ');
return newSpaced;
}
Just change the values before they are assigned? Place this before your variables are declared.
document.getElementById("txtOrderNumberRelease1").value = '987';
document.getElementById("txtOrderNumberRelease2").value = '654';
document.getElementById("txtOrderNumberRelease3").value = 'LLA';
The following code should update based on the values of a, b, and c...
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY";
var a = document.getElementById("txtOrderNumberRelease1").value;
var b = document.getElementById("txtOrderNumberRelease2").value;
var c = document.getElementById("ddlOrderNumberRelease3");
mainString = mainString.replace("789",a);
mainString = mainString.replace("456",b);
mainString = mainString.replace("LLX",c);

JQuery multiply and add

Let's say I have some numbers that I want to multiply and add.
var a = 5;
var b = 10;
var c = 2;
var d = 3;
I want to sum b and c then multiply that by a, then add d. Easy right?
If if were a normal equation the formula would look like: (a * (b + c) + d)
But how do I do that in JQuery?
(Note: the reason for JQuery is that I'll be getting these numbers from fields and divs... and placing a total elsewhere, etc.)
By default script language does not know type as int or float. So you can fix that by multiplying 1 to the value you expect to be a number.
var a = 5;
var b = 10;
var c = 2;
var d = 3;
var total = a*1 * (b*1 + c*1) + d*1;
convert your value into float or integer first before you do calculation. Example:
var a = parseFloat($(this).val());
var b = parseInt($("#b").attr("data"));
var c = (a+10)*b;
$("#result").text(c.toFixed(2));
Just store the values in variables before you apply them to the equation:
var a = +$("#input1")[0].value;
var b = +$("#input2")[0].value;
var c = +$("#input3")[0].value;
var d = +$("#input4")[0].value;
$("#output")[0].value = a*(b+c) + d;
The plus sign before the jquery function is there to force the string value into a Number value.
Correct JQuery is 100% javascript.
Although, worth mentioning just use parseint() for the values that you get from text field
You can still do the calculation using normal javascript, just refer to the contents using jQuery selectors if necessary.

Categories