Add together numbers in separate DIVs - javascript

(obligatory I'm new to this) What I am trying to do is...
Fetch the contents (a number) of the DIV ID.
Add those numbers together
Print them in the "at" DIV.
I know it should be pretty darn simple. But I cant wrap my head around why it isn't working. I want to learn WHY it's not working. I dont necessarily want you guys to write it for me. I want to learn. Here is my code...
var at = document.getElementById("a-total");
var ac = document.getElementById("a-coffee").innerHTML;
var ah = document.getElementById("a-hobby").innerHTML;
var af = document.getElementById("a-fundme").innerHTML;
var addopt = ac + ah + af;
function aTotal (){
if (addopt >= 0){
at.innerHTML = addopt;
} else {
console.log("tis broken");
}
}
aTotal();
It outputs properly, but it's just not adding the numbers in the DIVs together. It's placing them side by side rather than adding them together.

That's because you are only doing a string concatenation.
You need to transform the values to numbers as .innerHTML() returns a string. This is how should your operation:
var addopt = +ac + +ah + +af;
Note:
It's better to use .innetrText() or .textContent() over .innerHTML to avoid getting HTML markups inside your elements if there are any into the result.

This happens a lot. What you need to do is convert to integer because it reads it as a string using ParseInt (variable) or ParsefLoat (variable) ParsefLoat (variable) can also use .toFixed (decimal_places)

You have to parse the content of the divs to a number, as the innerHTML returns a string.
So either var addopt = +ac + +ah + +af; or var addopt = parseInt(ac) + parseInt(ah) + parseInt(af); should work for you.

You need to parse the innerHTML to integers or floats to be able to do mathematical operations on them. Check the below code that takes the text and parses it to ints:
var addopt = parseInt(ac) + parseInt(ah) + parseInt(af);

You try to additionnal strings instead of numbers.
innerHTML return the string in a HTML element.
You should parseInt or parseFloat the content to have numbers.
<script>
var at = document.getElementById("a-total");
var ac = document.getElementById("a-coffee").innerHTML;
var ah = document.getElementById("a-hobby").innerHTML;
var af = document.getElementById("a-fundme").innerHTML;
// Values are taken as string and mus be converted to int.
// We check also that a value is not undefined.
ac = isNaN(parseInt(ac)) ? 0 : parseInt(ac);
ah = isNaN(parseInt(ah)) ? 0 : parseInt(ah);
af = isNaN(parseInt(af)) ? 0 : parseInt(af);
var addopt = ac + ah + af;
function aTotal (){
if (addopt >= 0){
at.innerHTML = addopt;
} else {
console.log("tis broken");
}
}
aTotal();
</script>

The contents of your divs are strings, even though the represent numbers. So if your divs have the values '1', '2' and '3' adding them togther gives you '123' rather than 6 as you might expect. Have a look at the parseInt function to see how you can turn your strings into numbers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Related

How to add one to a variable to make 2 not 11

Currently this makes 11. It's for a slideshow and the var "n" equals 1 by default
function forward() {
document.getElementsByClassName("img")[0].setAttribute("class","imgout");
setTimeout( function() {
var n1 = document.getElementById("img").getAttribute("data-number");
var n=n1+1;
document.getElementById("img").setAttribute("data-number", n);
document.getElementById("img").setAttribute("src", "images/" + n + ".jpg");
document.getElementsByClassName("imgout")[0].setAttribute("class","img");
}, 500)
}
Use parseInt():
var n = parseInt(n1, 10) + 1;
Instead of:
var n=n1+1;
When n1 will be a string, because it came from the DOM, you need to convert n1 to an integer. There are many ways to do this, and really you should probably use a regular expression to validate that n1 contains what you expect first, but that being said you can try any of the following:
var n=parseInt(n1, 10)+1;
var n=(n1*1)+1;
var n=(+n1)+1;
As an aside the regex for validating the input from the DOM might be something such as:
/^-?\d+$/
Use Number():
var n = Number("1");
FIDDLE
parseInt - good choice. Also you can do
var n = n-0+1
Just remember that of you have different types "+" will convert to string and "-" will convert to numbers
Convert n1 to number as it is a string like ~~n1. The ~~n1 form is good if you know you want an integer (a 32-bit integer).
Second way is to use Number() function i.e. Number(n1) will convert n1 value into a string.
var n=parseInt(n)+1;
Documentation
Fiddle

Increase value of digit within HTML string (jQuery)

I have a bunch of images in a folder which are all named as numbers. The first one is displayed on document load.
<img src="image/01.jpg" />
I want to use jQuery to flick through the images. In other words, I want to convert the HTML to a string and then increase the value of what is currently "01".
So far I have:
$(document).ready(function(){
$("button").click(function(){
var $n = $("img").html(htmlString(17));
$n.val(Number($n.val())+1);
});
});
The bit that I'm sure I'm completely wrong on is the selecting of the digit (i.e delcaring var $n. I've tried to convert the HTML to a string there and count along the characters but I'm not even sure if that's the right route to be taking; I can't find anything similar anywhere.
Thanks.
img element doesn't have html content, apart from that you are using html as setter not getter. You can replace the src attribute's value using replace method:
$('img').prop('src', function(_, src) {
return src.replace(/\d+/, function(n) {
var num = +n + 1;
return num.toString().length === 1 ? '0' + num.toString() : num;
});
});
http://jsfiddle.net/Bb84Q/
You can just
1)catch the src value in a js variable
2) using substr function get rid of the "image/" part.
3) Then using split() on "." take the first array slot's value.
4)Convert that to integer using intVal() and
5) then increment the value
var source = "image/01.jpg";
var number = source.split(".")[0].split("/")[1];
number = (number *1) + 1
var newsource = "image/" + number + ".jpg";
this is how you'd actually get source
var source = $("img").attr('src');
just realized that this will make "image/2.jpg" , you could use a data-number attribute, you could re-name the images that are 1 - 9 , but this gives you an idea

Performing mathematical operations on attribute value

I am attempting to perform mathematical operations with JavaScript on values obtained from an attribute. The attribute is created via a PHP loop. I will give an example of one of the html tags containing the attributes, but keep in mind that there are many of these tags which contain unique attribute values.
The HTML:
The JavaScript(jQuery):
$("a[href^='secondary_imgs.php']").click(function(){
var pageWidth = $(window).width();
var maxshadowWidth = (Math.floor(pageWidth * 0.91808874)) - 2;
var mWidth = $(this).attr("mwidth");
var maxSecondaryWidth = mWidth + 60;
alert (maxSecondaryWidth);
if(maxSecondaryWidth <= maxshadowWidth) {
var shadowWidth = maxSecondaryWidth;
} else {
var shadowWidth = maxshadowWidth;
}
var shadowboxrel = 'shadowbox;width=' + shadowWidth;
$(this).attr('rel', shadowboxrel);
The operation doesn't seem to be working, and I have a feeling it has to do with my lack of experience using mathematical operations in javascript. In this case, I think something is wrong with my method of using the attribute value, in the mathematical operation.
For example, the above width attribute is defined as 593. I define the maxSecondaryWidth as mWidth + 60. I fired an alert to see what value I was getting. It should have been shown as 653, yet the value that is 'alerted' is 59360. Obviously I don't understand how to add, as the + is concatenating the two values, as opposed to adding them together. Could it have to do with needing to transform the attribute value from a string into an integer?
You have to convert to a number using parseInt(), otherwise + will do string concatenation:
var mWidth = parseInt($(this).attr("mwidth"), 10);
If the attribute can also be a float, use parseFloat() instead of parseInt().
Do this to make sure mwidth is a number:
var mWidth = parseInt($(this).attr("mwidth"), 10);
Otherwise, + will perform a string concatenation. Alternatively, if you need mwidth to be a floating point number, do this:
var mWidth = parseFloat($(this).attr("mwidth"));
You can do a couple things:
parseInt(mWidth, 10); // int
parseFloat(mWidth); // float
Number(mWidth); // number
otherwise javascript will believe it's a string.
Some less common conversions:
mWidth | 0; // int (javascript bitwise operations are 32-bit signed intergers)
+mWidth; // force Number
i think that you must do something safer (as it is always better);
You should check if it is a number or not:
DOM:
JS:
$("a[mwidth]").each(function(){
var $attr = $(this).attr('mwidth');
if(!isNaN($attr)){
sum += (parseInt($attr));
}
});
If you remove the condition the results will be NaN
Take a look at : http://jsfiddle.net/zVwYB/

jquery , ajax data sum cant get to work correctly

$.post('ajax_ceneizbaze.php', function(cenovnik){
if(cenovnik){
cenastr=cenovnik.cenastrana;
cenadinamika=cenovnik.cenadinamika;
cenabaza=cenovnik.cenabaza;
cenakorpa = cenovnik.cenakorpa;
cenacms = cenovnik.cenacms;
inkrementodrzavanje = cenovnik.cenaodrzavanje;
rezz = parseInt(cenastr+cenadinamika);
alert(rezz);
}
else alert('bla bla..');
},'json');
initial value for cenastr is 25, and for cenadinamika is 50 ,Ajax works perfectly in this mine example, but when i try to sum values cenastr and cenadinamika i get output 2550 , instead 75? why i cant convert that to integer and to get sum of thoose two. it only output result in string format. i tried parseInt to place before sum operation but it doesnt helps.
you have to parseInt each of the strings:
rezz = parseInt(cenastr) + parseInt(cenadinamika);
Try that out
http://www.javascripter.net/faq/convert2.htm - this might help. You need to convert the strings to numbers before the calculation!
The + operator has a dual purpose. On strings it concatenates them:
"25" + "50" = "2550"
With numbers, it sums them.
25 + 50 = 75
Therefore we can deduce that your two variables are strings, and that you parse the result of concatenating them to an integer, giving you 2550.
You need to parse each individual value to an int before using the + operator to add them:
rezz = parseInt(cenastr,10) + parseInt(cenadinamika,10);
Make sure the variable are numbers before adding:
cenastr= +cenovnik.cenastrana;
cenadinamika= +cenovnik.cenadinamika;
//...
rezz = cenastr + cenadinamika;
parseInt will be working on the result of the addition, which, both being strings, will be the concatenation.
Either:
parseInt(cenastr) + parseInt(cenadinamika)
or use the unary operator:
(+censtr) + (+cenadinamika);

How to add together numerical values that are stored in strings?

I'm trying to add 1 to my JavaScript variable, but the following code doesn't give expected results:
var val1 = document.getElementById('<%= rng1.ClientID %>');
var val2 = val1.value + "1";
alert(val2.value);
How can I do this?
you can use the function parseInt() to transform the string stored in val1.value into a number:
var val2 = parseInt(val1.value) + 1;
Note that Number(val1.value) will also convert your value into a number.
-edit-
As yc suggest, is highly recommended to use parseInt(val1.value, 10) + 1; because if your string starts with a "0" the string is interpreted as octal. eg. parseInt("0123") == 83 and not 123
The simplest and also preferred way would be to use + to cast to a number.
Examples:
+'234'; // 234
+'042'; // 42! It does not convert to octal
In your case:
var val1 = +(document.getElementById('<%= rng1.ClientID %>').value); // () added just for the looks
var val2 = val1.value + 1; // if val1 is 5, val2 will be 6 hooray!
alert(val2); // just val2, since it's a plain number not an html input element
parseInt($('.scpContainer').height()+200)
you must add number, so try it without quotes :-)
In an external JavaScript file you can't use the <%=ControlID.ClientID %> to get the client id.
If there you using an external JavaScript file you need to pass client id value to that function.

Categories

Resources