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

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

Related

Add together numbers in separate DIVs

(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

Removing an integer from an id

I have an id:
div id ="untitled-region-5"
I want to grab that id and remove 4 from it and then do some code with the new id.
So far I am trying something like this from reading about how to perform this:
var n = $(this).attr('id').match(/untitled-region-(\d+)/)[1];
But I don't know how to remove 4 from the integer.
It's still a string, that's why you can't easily use it in math. Some operations work, because they will implicitly convert the value to a number.
Use parseInt to explicitly do the conversion, so that you know what you have:
var n = parseInt($(this).attr('id').match(/\d+$/)[0]);
n -= 4;
var id = $("div").attr("id");
var n = parseInt(id.substring(id.lastIndexOf("-") + 1), 10);
I made a jsFiddle too: http://jsfiddle.net/YEWQQ/
<div id ="untitled-region-5">​
just take n and subtract 4
var n = $('div').attr('id').match(/untitled-region-(\d+)/)[1];
var newNumber = n-4;
$('div').attr('id','untitled-region-'+newNumber);

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.

jQuery / javascript variable in if statement not working

I have a variable as such:
var is_last = $('.paging a:last').attr('rel');
this returns '-400' which is correct.
However, i need to add 200 to this so the answer is '-200'
if i do this:
var is_last = $('.paging a:last').attr('rel')+200;
the variable is now '-400200'
How can i pass the variable as a value?
A.
You need to parse the output of .attr(), it to an integer first using parseInt() so you're dealing with a number (and not a string), like this:
var is_last = parseInt($('.paging a:last').attr('rel'), 10) + 200;
I reckon that #Nick Craver is correct and that parseInt is the more correct answer, but as a quick-and-dirty alternative you can also convince javascript that a variable is a number and not a string by multiplying by 1:
var x = parseInt("-400", 10) + 200;
var y = ("-400" * 1) + 200;
alert(x);
alert(y);

javascript parseFloat '500,000' returns 500 when I need 500000

How would it be a nice way of handling this?
I already thought on removing the comma and then parsing to float.
Do you know a better/cleaner way?
Thanks
parseFloat( theString.replace(/,/g,'') );
I don't know why no one has suggested this expression-
parseFloat( theString.replace(/[^\d\.]/g,'') );
Removes any non-numeric characters except for periods. You don't need custom functions/loops for this either, that's just overkill.
Nope. Remove the comma.
You can use the string replace method, but not in a one liner as a regexp allows.
while(str.indexOf(',')!=-1)str= str.replace(',','');
parseFloat(str);
Or to make a single expression without a regexp=
return parseFloat(str.split(',').join(''));
I'd use the regexp.
I don't have enough reputation to add a comment, but for anyone wondering on the performance for regex vs split/join, here's a quick fiddle: https://jsfiddle.net/uh3mmgru/
var test = "1,123,214.19";
var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
var a = parseFloat(test.replace(/,/g,''));
}
var t1 = performance.now();
document.write('Regex took: ' + (t1 - t0) + ' ms');
document.write('<br>')
var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
var b = parseFloat(test.split(',').join(''));
}
var t1 = performance.now();
document.write('Split/join took: ' + (t1 - t0) + ' ms');
The results I get are (for 1 million loops each):
Regex: 263.335 ms
Split/join: 1035.875 ms
So I think its safe to say that regex is the way to go in this scenario
Building on the idea from #kennebec, if you want to make sure that the commas are correct, and you don't want to replace commas, you could try something like this:
function myParse(num) {
var n2 = num.split(",")
out = 0
for(var i = 0; i < n2.length; i++) {
out *= 1000;
out += parseFloat(n2[i])
}
return out
}
alert(myParse("1,432,85"));
// Returns 1432085, as the comma is misplaced.
It may not be as fast, but you wanted alternatives :)
What about a simple function to solve most of the common problems?
function getValue(obj) {
Value = parseFloat( $(obj).val().replace(/,/g,'') ).toFixed(2);
return +Value;
}
The above function gets values from fields (using jQuery) assuming the entered values are numeric (I rather validate fields while user is entering data, so I know for sure field content is numeric).
In case of floating point values, if well formatted in the field, the function will return a float point value correctly.
This function is far from complete, but it quickly fix the "," (comma) issue for values entered as 1,234.56 or 1,234,567. It will return valid number as far the content is numeric.
The + (plus) sign in front of the variable Value in the return command is a "dirty trick" used in JavaScript to assure the variable content returned will be numeric.
it is easy to modify the function to other purposes, such as (for instance), convert strings to numeric values taking care of the "," (comma) issue:
function parseValue(str) {
Value = parseFloat( str.replace(/,/g,'') ).toFixed(2);
return +Value;
}
Both operations can even be combined in one function. I.e.:
function parseNumber(item,isField=false) {
Value = (isField) ? parseFloat( $(item).val().replace(/,/g,'') ).toFixed(2) : parseFloat( item.replace(/,/g,'') ).toFixed(2)
return +Value;
}
In such case, if function is called result = parseNumber('12,092.98'); it will parse the value as it is a String. But if called as result = parseNumber('#MyField', true); it will try to obtain the value from '#MyField'.
As I said before, such functions are far from complete, and can be expanded in many ways. One idea is to check the first character of the given parameter (string) and decide based on the string format where to obtain the value to be parsed (if 1st character is = '#' then it is an ID from a DOM object, otherwise, if it begins with a number, it must be a string to be parsed).
Try it... Happy coding.

Categories

Resources