Pure Javascript - Turn number into a % - javascript

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>

Related

Type Conversion Issue(?): How to grab html <span> tag's value and perform math on it?

How would I use javascript to take 30% off of the price and then append the discounted price under the old price? I'm getting tripped up on this.
Someone advised that I need to remove the $ some other way...?
HTML
<span class="price">$59.00</span>
JavaScript
var priceOne = parseInt(document.querySelector(".price").innerHTML);
var priceTwo = "$" + priceOne * .70;
document.querySelector(".price").innerHTML = priceTwo;
All tips or advice or solutions is appreciated!
JavaScript isn't able to parse strings to numbers if they have a string in it for whatever reason.
var price = document.getElementsByClassName('price')[0];
price.innerHTML += '<br>$' + (parseFloat(price.innerHTML.replace('$', ''))*0.7).toFixed(2);
<span class="price">$59.00</span>
You can use regular expressions
var priceOne = document.querySelector(".price").innerHTML;
// Use regular expression to strip out all non-numbers
var re = /\.\d+|\d\/\d|\d/g
var result = priceOne.match(re).join('');
//if in the united states, use this, else look on MDN for the correct formatting
document.querySelector(".price").innerHTML = (result*.7).toLocaleString("en-US",{style:"currency",currency:'USD'})
let oriprice = document.getElementById('price').innerHTML;
let priceOne = parseFloat(oriprice.substring(1,oriprice.length));
var priceTwo = "$" + (priceOne * .70).toFixed(2);
console.log(priceTwo)
<span id="price">$59.00 </span>
The problem is that your priceOne was NaN after parsed. Try to use subString to remove the first $ sign, and since it's a decimal amount, instead of using parseInt, use parseFloat and after calculating the 70% of it, apply toFixed on it

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;

Simple JS function using text inputs and parseInt, returns NaN

Can anyone help me figure out why I keep getting a NaN result?
function showShares() {
var tot = document.getElementById('total').innerHTML;
var pri = document.getElementById('price').innerHTML;
var per = document.getElementById('percent').innerHTML;
var shar = parseInt(tot, 10) * parseFloat(per) / parseFloat(pri);
document.getElementById("shares").innerHTML=Math.round(shar);
}
<td><text id="price"><%= StockQuote::Stock.quote(current_user.fund1).last %></text></td>
<td><text id="shares"></text></td>
<td><text id="percent">.50</text></td>
<p class="alignright1"><input type="text" id="total" size="8"></input>
<br><a href onclick="showShares()">here</a>
The stock quote is returning an integer in the cell ie. 25.38. it returns the same NaN if I remove the embedded ruby and place a simple integer ie. 50. The same is true if I replace the input with a number.
Thank You
Try this :
function showShares() {
var tot = document.getElementById('total').innerHTML;
var pri = document.getElementById('price').innerHTML;
var per = document.getElementById('percent').innerHTML;
var shar = parseInt(tot, 10) * parseFloat(per, 10) / parseInt(pri, 10);
document.getElementById("shares").innerHTML=Math.round(shar);
}
The percent value is a float (digit with comma) and must be interpreted by the JS engine like a float ;)
You are trying to get a value from an input element with this code,
document.getElementById('total').innerHTML
That's not the way to get the value from the input. You should use this code,
document.getElementById('total').value

Sum two values in 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

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);

Categories

Resources