Sum two values in javascript - javascript

this I think will be stupid question, but here it goes.
I need to dynamically add a div and give it ID + 1 depending on last added div's ID of previously added element.
the div is
<div id="file-uploader-0" class="file-uploader"></div>
So I roughly came out with that code:
$('#addOneMoreFileOrGroup').on('click', function(){
var latestFileUploaderId = $('.well-large .file-uploader').last().attr('id').split('-')[2] + 1;
$('.well-large .control-group:last').after('<div class="control-group deal-type-online"> \
<label class="control-label">File / File Group Title:</label> \
<div class="controls"> \
<input class="span4 file-title" type="text"> \
<span class="question label label-warning" data-title="File / Group Name:" data-content="Name for your file or group of related files (for example your brand logotype in different file formats)." data-original-title="">?</span> \
<div id="file-uploader-' + latestFileUploaderId + '" class="file-uploader"></div> \
</div> \
</div>');
});
But the problem is that in the end of all that I receive "file-uploader-01", "file-uploader-011", "file-uploader-0111".
I tried to use "latestFileUploaderId++" which giving me right result once as "1" and after going as "11", "111", "1111".
Thank you for the tips and help!

Change this:
var latestFileUploaderId = $('.well-large .file-uploader').last().attr('id').split('-')[2] + 1;
to this:
var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2],10) + 1;

You're adding a string to a number, which causes the + operator to do string concatenation.
Convert the string to a number first.
var latestFileUploaderId = parseFloat($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;

Convert the string from the id to integer to increment it correctly:
var lastID = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]);
var latestFileUploaderId = lastID + 1;

var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2],10) + 1;
You are cocatenating a string and a number... parseInt will convert the string to its numerical value and then the addition will work.

You should use parseInt:
var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;

You can use parseInt() to convert the id to a number.
var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;

$('.well-large .file-uploader').last().attr('id').split('-')[2]
is a string. You need to parse it to a int(float).
try using parseInt, parseFloat

You need to cast the value to a Number. Like this:
var latestFileUploaderId = Number($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;

As others have said, you need to change the variable to a Number first, but I wouldn't use parseInt() or similar. Instead, multiplying by 1 is much faster, so something like this is what I'd recommend:
var last = $('.well-large .file-uploader').last().attr('id').split('-')[2];
var latestFileUploaderId = (last * 1) + 1;

JavaScript uses the + operator to concatenate strings which happens in your case. Only numerical types are summarized arithmetically.
In order to increment the ID you have to cast it to an integer before.
console.log ('1' + 1 );
String '11'
console.log( parseInt('1') + 1 )
Int 2

Related

How can I convert the string value of a jQuery object into an actual jQuery object?

I have this string in my JS code right now:
newWords = '$(p span.word[style="--' + paraIndex + 'word-index:undefined"], p span.whitespace[style="--' + paraIndex + 'word-index:undefined"])';
I want to convert this string into a jQuery object that I can use do identify those specific elements.
I also saw the eval() function. That looks like it does what I want it to, but is super unsafe/unsecure.
Does anyone know a safe way to do this?
The simplest solution is to remove $( and ) and pass the remaining string as an argument to $():
var paraIndex = 0;
var newWords = '$(p span.word[style="--' + paraIndex
+ 'word-index:undefined"], p span.whitespace[style="--'
+ paraIndex + 'word-index:undefined"])';
var jQ = $(newWords.slice(2, -1));
console.log(jQ);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Pure Javascript - Turn number into a %

My program spits out a number between 0 and 1, and I cant change that. I need to turn it into a % to use as a variable for a CSS selector.
<div id="Value">0.50</div>
<script>
var element = document.getElementById("Value");
var percent = element * 100;
</script>
But how am I meant to put a % symbol on the end so I can do this:
document.getElementById("circle").style.marginLeft = percent;
Any help would be appreciated, thank you.
String concatenation:
document.getElementById("circle").style.marginLeft = percent + "%";
Since "%" is a string, percent will get converted to string and then the result will be the percent value followed by "%".
As Federico pointed out, you should be using either .value (if the id="Value" element is a field element [an input, textarea, or select]) or .textContent or .innerHTML (if it's not). In your case, it's a div, so textContent would make sense:
var value = document.getElementById("Value").textContent;
var percent = value * 100; // Implicitly converts `value` to number
document.getElementById("circle").style.marginLeft = percent + "%"; // Implicitly converts `percent` to string
try
circle.style.marginLeft = Value.innerText*100 + '%'
<div id="Value">0.50</div>
<div id="circle">◉<div>
document.getElementById("circle").style.marginLeft = percent + '%';
When used on strings, the + operator is called the concatenation operator.
Reference: Javascript Operators
This should solve it.
document.getElementById("circle").style.marginLeft = percent+"%";
In Javascript you can concat natively an int and a string using the '+' operator which means that -
var a = 5
var b = a + '%'
result is b = '5%'
Use innerHTML to get the text from the element
var element = document.getElementById("Value").innerHTML;
var percent = parseFloat(element)*100;
percent+='%';
console.log(percent)
<div id="Value">0.50</div>

Using the ".value" property of a textbox in Javascript

document.getElementById("t3").value = document.getElementById("t1").value +
document.getElementById("t2");
Through above code I could not get the result of addition of two numbers.
If you want to add those to values, you have to convert them to integer at first. .value always holds a string.
parseInt(document.getElementById("t1").value, 10) + parseInt(document.getElementById("t2").value, 10);
You are not actually adding two numbers together. You are attempting to add document.getElementById("t1").value (which is a string containing with numbers in it) to document.getElementById("t2"), which is a DOM element.
You probably get a result like this:
43[object HTMLInputElement]
You need to (a) get the value property of the second element and (b) add them together as numbers, rather than as strings.
document.getElementById("t3").value = (+document.getElementById("t1").value) +
(+document.getElementById("t2").value);
(+document.getElementById("t1").value) converts the value into a number. It is the unary plus + operator.
Try this:
document.getElementById("t3").value = parseInt(document.getElementById("t1").value,10) +
parseInt(document.getElementById("t2").value,10);
This is cheeky, but on the off-chance the t3 element that the OP is trying to update is a div or span rather than an input :)
var t1, t2, t3;
t1 = document.getElementById("t1");
t2 = document.getElementById("t2");
t3 = document.getElementById("t3");
t3.innerHTML = parseInt(t1.value, 10) + parseInt(t2.value, 10);
Or
t3.innerHTML = +t1.value + +t2.value;

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

JavaScript Calculation Problem - NaN message

I'm calculating a total number. I get the sum values from div's. But in total, instead of numbers I get (NaN - Not a Number)
JavaScript Function:
<script type="text/javascript">
function calculateTotal(){
var total = document.getElementById('valor1').innerHTML*1 + document.getElementById('valor2').innerHTML*1 + document.getElementById('valor3').innerHTML*1 + document.getElementById('valor4').innerHTML*1 + document.getElementById('valor5').innerHTML*1 + document.getElementById('valor6').innerHTML*1;
document.getElementById('total').innerHTML = total;
}
</script>
EDIT:
I found the error, I had a closing tag inside the DIV's like this:
<center><div id="valor1"></center></div>
Changed to:
<center><div id="valor1"></div></center>
You cannot use document.getElementById('valor1').innerHTML directly. You have to convert this to number. Please try this.
var value = document.getElementById('valor1').innerHTML;
var number = parseFloat(value)||0;
Do this for each div innerHTML which have number.
var number = parseFloat(value)||0;
The above line will help you to assign 0 to value if div is empty or div html cannot be converted to a number.
Use parseFloat(document.getElementById('x').innerHTML) to convert them to numbers before performing operations:
var total = parseFloat(document.getElementById('x1').innerHTML) + parseFloat(document.getElementById('x2').innerHTML);
You also may want to check them if they're numeric, here's a simple test using isNaN:
alert((isNaN("23"))?'not number':'number');
HTML:
<div id="valor1">2</div>
<div id="valor2">2</div>
<div id="valor3">ccccc</div>
<div id="valor4">2</div>
<div id="valor5">2</div>
<div id="valor6">2</div>
<hr/>
<div id="total">0</div>
JavaScript:
function $(id) { return document.getElementById(id); }
function get(elem) { return parseFloat($(elem).innerHTML) || 0; }
(function() {
var total =
get('valor1') * 1 + get('valor2') * 1 + get('valor3') * 1 +
get('valor4') * 1 + get('valor5') * 1 + get('valor6') * 1;
$('total').innerHTML = total;
}());
A little optimization of the work and demo.
But why stop here? :) we can make it even better ( I think ):
function get(elem) {
return (parseFloat($(elem).innerHTML) || (function() {
$(elem).innerHTML += " <i>Not a number assumed 0</i>";
return 0;
}()));
}
And the updated demo.
Edit: no errors on Chrome & Mozilla (Linux).
try using parseInt() as in
var total = parseInt(document.getElementById('valor1').innerHTML)*1 + parseInt(document.getElementById('valor2').innerHTML)*1 + ... ;
etc etc
this will ensure that what you're getting out of the fields is in fact, a number
Did you try to put these parts into brackets?
(document.getElementById('valor1').innerHTML * 1) + ...
See: http://rx4ajax-jscore.com/ecmacore/operator/predence.html
Even better - use the parseInt(var string) function;
parseInt(document.getElementById('valor1').innerHTML) + ...

Categories

Resources