Javascript/Jquery : Mathematically Divide Two Variables - javascript

Here's my code:
var frameWidth = 400;
var imageWidth = $('#inner-image').css('width');
var numberOfFrames = imageWidth/frameWidth;
How do I make "numberOfFrames" display as a quotient? I.E. process "frameWidth" and "imageWidth" as numbers, rather than objects?
Let me know if I need to explain myself more clearly. Thanks!

.css('width') is likely returning the value with px. You can use parseInt() to get only the number.
var frameWidth = 400;
var imageWidth = parseInt( $('#inner-image').css('width'), 10);
var numberOfFrames = imageWidth/frameWidth;
The second argument 10 specifies the base that parseInt() should use.
You can also use the width()(docs) method to get the result without the px.
var frameWidth = 400;
var imageWidth = +$('#inner-image').width();
var numberOfFrames = imageWidth/frameWidth;
Here I used the unary + operator to make it a Number instead of a String.

Related

Javascript return a NaN value after a math operation

Ok, I'm not a coder, I've no school about it but ... I can't figure out why this little operation returns a NaN value!
I've this var at the beginning
// Varialbes for simulation purpose
var Simulation = false;
var FakeCapital = 0;
var PercentOfTotal = 100;
// Variables
var Capital = (engine.getBalance() / 100).toFixed(2);
var UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
var StartingBalance = UsableBalance;
if (FakeCapital > 0 && Simulation) {
Capital = FakeCapital;
UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
StartingBalance = UsableBalance;
}
So If I activate the similation var and if I want to use another capital, the script use the fakecapital to test my script.
Here all works but I think that here there's the problem, specially the UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
Because when the script run:
If I don't use the simulation, all goes right
If I use the simulation and the fake capital, all goes right
But if I use the simulation and I want to use the real capital, the UsableBalance var is strange, not immediately but when the script runs! I try to explain better
Let's assume that I use the simulation phase and I want to use the real capital
Your ballance is: 87.26 bits.
I'll use: 87 bits for this session, as your request.
Here all ok, but this code:
if (TemporaryLoss <= 0) {
Capital += LastProfit;
UsableBalance = Math.floor((PercentOfTotal / 100) * Capital);
TemporaryLoss = 0;
}
Return this:
TemporaryLoss: 0
Capital: 87.26
LastProfit: 1.0299999999999998
PercentOfTotal: 100
Capital: 87.261.0299999999999998
Why the math return this strange number? like a concatenation of 2 numbers? Seems that the script use the var like a text and not like a numbers.
Any Idea?
You make a string with toFixed()
var Capital = (engine.getBalance() / 100).toFixed(2);
and used it later as number, but it is a string.
Capital += LastProfit;
Solution: If fixed is necessary, then use parseFloat() to make a number again.
Lets take an example :
var x = 1;
var y = '1';
var z = x + (y*10)
the datatype of variable y is implicitly coerced to number for the current operation, to evaluate the value of z.
So, for z , y is taken as a number because (y*10) caused implicit coercion, but doesn't change y itself to number
In your case ,
var Capital = (engine.getBalance() / 100).toFixed(2);
causes Capital to become a string.
Hence any further addition operations with Capital result in concatenation
You will have to explicitly convert to int or float as mentioned earlier.

function to get percentage in JavaScript and return decimal value

I have this JavaScript function (see below). It only return whole number, it only works when I inputted a whole number. But when I inputted decimal value it doesn't work.
What should I do to handle decimal value?
function calc()
{
var license=parseInt(document.getElementById("license").value);
var service=parseInt(document.getElementById("service").value);
var amount=parseInt(license)+parseInt(service);
var mult=service*(parseInt(document.getElementById("preterms").value) / 100);
var mult1=service*(parseInt(document.getElementById("blueterms").value) / 100);
var mult2=service*(parseInt(document.getElementById("configterms").value) / 100);
document.getElementById("amount").value = amount;
document.getElementById("pre").value = mult;
document.getElementById("blue").value = mult1;
document.getElementById("config").value = mult2;
}
Thanks in advance.
change parseInt to parseFloat, like
var license=parseInt(document.getElementById("license").value);
to
var license=parseFloat(document.getElementById("license").value);
Since you are working with decimal values You need to use parseFloat instead of parseInt
ex:
function calc() {
var license = parseFloat(document.getElementById("license").value);
var service = parseFloat(document.getElementById("service").value);
var amount = parseFloat(license) + parseFloat(service);
var mult = service * (parseFloat(document.getElementById("preterms").value) / 100);
var mult1 = service * (parseFloat(document.getElementById("blueterms").value) / 100);
var mult2 = service * (parseFloat(document.getElementById("configterms").value) / 100);
document.getElementById("amount").value = amount;
document.getElementById("pre").value = mult;
document.getElementById("blue").value = mult1;
document.getElementById("config").value = mult2;
}
It looks like folks suggested using parseFloat. The next issue you're likely to run into is formatting the output. You can use toFixed to output your percentages with a fixed number of decimals:
(12.34567).toFixed(2)
// => "12.35"

trouble with comparing strings in javascript

I'm having a weird issue in JS comparing strings. One string is from a user input.
y = data;
document.getElementById("typeThisWord").innerHTML = y;
x = document.getElementById("inputField");
document.getElementById("youTyped").innerHTML = x.value;
first = document.getElementById("youTyped");
second = document.getElementById("typeThisWord");
if(first==second) correct=true;
When the words are the same, it still comes out false. I added in the 'first' and 'second' variables just to see if it would make a difference. Previously I've tried just comparing 'x' to 'y'. I've also tried x.value==y, x==y.value, and x.value==y.value. THe same with 'first' and 'second.' Surprisingly first.value==second.value came out to be true all the time, even when it shouldn't be.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var x, y;
var first, second;
var availV = window.innerHeight - 100;
var availH = window.innerWidth - 100;
var randV, randH;
var correct = new Boolean(); correct=true;
var imageX;
function displayWord() {
if(correct) {
correct=false;
$.ajax({
url: "http://localhost:25578/TypeGood/VisitsSession",
success: function(data) { y = data; },
async: false
});
document.getElementById("typeThisWord").innerHTML = y;
imageX = document.createElement("img");
imageX.src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRPRV4XdE7C9sa0pM-FeXcOSQydg7Sh0INg-ZD6FKZ4wjY8WPHa5Q";
imageX.height = 100;
imageX.width = 100;
imageX.style.position = "absolute";
randV = Math.round( Math.random() * availV );
randH = Math.round( Math.random() * availH );
imageX.style.top = randV + "px";
imageX.style.left = randH + "px";
imageX.style.zIndex = "-20";
document.body.appendChild(imageX);
}
x = document.getElementById("inputField");
document.getElementById("youTyped").innerHTML = x.value;
first = document.getElementById("youTyped").innerHTML;
second = document.getElementById("typeThisWord").innerHTML;
if(first==second) {correct=true;}
x.value = "";
}
</script>
getElementById returns a reference to a DOM element, not a string, so you're not comparing strings, you're comparing DOM elements. Since they're different elements, they aren't ==.
At a minimum, your last three lines should be something like:
first = document.getElementById("youTyped").innerHTML;
second = document.getElementById("typeThisWord").innerHTML;
if(first==second) correct=true;
(E.g., using the innerHTML of the elements, which is a string.) Although I think I'd probably keep the values around in variables rather than going back to the DOM for them.
For Example:
y = data; //data is string value "First"
Change this value to new string "first" >> here f is small
y2 = "first"
Now, When both are of same type, its case sensitive.
if(y==y2)
so values are..
First == first
that will be false.
So make sure of data you are passing in inner html. and make sure you are not adding some white space to it..
I hope this may solve problem. :)
comment back if not solved after modifying the code :)
use this instead of (first==second):
if(first===second)
and retrieve value from html like this:
first = document.getElementById("youTyped").innerHTML;

Programmatically determine the height of a div element

I'm trying to get the height of a div, then position it based on the height. I've read various articles on this, but I always seem to be getting NaN as a result. Yes the javascript is loaded at the end of the body, after the divs are drawn.
I'm using asp.net to create this javascript dynamically. What I have output so far is:
var resultsDiv = document.getElementById('resultsDiv');
var resultsInnerDiv = document.getElementById('resultsInnerDiv');
resultsInnerDiv.innerHTML = "test";
var h = parseInt(resultsInnerDiv.style.offsetHeight);
alert(parseInt(resultsInnerDiv.style.offsetHeight));
resultsInnerDiv.style.top = ((h / 2) -125) + 'px';
I need to get the actual height, instead of NaN. NaN pixels is obviously not valid.
I think this what you need:
var resultsDiv = document.getElementById('resultsDiv');
var resultsInnerDiv = document.getElementById('resultsInnerDiv');
resultsInnerDiv.innerHTML = "test";
var h = parseInt(resultsInnerDiv.offsetHeight);
alert(parseInt(resultsInnerDiv.offsetHeight));
resultsInnerDiv.style.top = ((h / 2) -125) + 'px';
offsetHeight is not a property of element.style, but the element itself (see here).
Try this:
var resultsDiv = document.getElementById('resultsDiv');
var resultsInnerDiv = document.getElementById('resultsInnerDiv');
resultsInnerDiv.innerHTML = "test";
var h = parseInt(resultsInnerDiv.offsetHeight);
alert(h);
resultsInnerDiv.style.top = ((h / 2) -125) + 'px';

JavaScript issue in IE when adding numbers

I have a simple form, with 5 textboxes and 3 answers (also textboxes). The form calculates a result for the user with number inputs. My problem is my calculation does not work in IE, but works fine in both Chrome and Firefox.
What's wrong?
Here is my function:
function addNumbers()
{
var val1 = Number(document.getElementById("value1").value);
var val2 = Number(document.getElementById("value2").value);
var val3 = Number(document.getElementById("value3").value);
var val4 = Number(document.getElementById("value4").value);
var val5 = Number(document.getElementById("value5").value);
var val6 = '100';
var ansD1 = document.getElementById("answer1");
ansD1.value = Number((val1 * val2) * (val4 / val6));
var ansD2 = document.getElementById("answer2");
ansD2.value = Number((val1 * val3) * (val5 / val6));
var ansD3 = document.getElementById("answer3");
ansD3.value = Number (ansD1.value - ansD2.value);
}
Change this line:
var val6 = '100';
to this:
var val6 = 100;
You want all your values to be actual numbers (not strings) so you can do math on them.
Also, you don't need the Number() in these lines because the result of the numeric math is already a number. Plus the assignment to the answer fields is just going to convert the result to a string anyway:
ansD1.value = Number((val1 * val2)*(val4/val6));
They can just be this:
ansD1.value = (val1 * val2)*(val4/val6);
The modified code works fine in IE here: http://jsfiddle.net/jfriend00/5WFRA/.
Instead of Number use parseInt, otherwise they are treated as strings

Categories

Resources