Reputation: 1
I'm very new to javascript coding and I know enough to structure a function/arguement, but not enough to troubleshoot.
Here's the portion of my code in question. I'm trying to yield a rounded integer value from a series of calculations, but I can't seem to get it to work.
If this worked correctly, it would grab the 20000 value, multiply it by 3 [60000], then divide that by 3250 [18.4615...], then round down to the nearest number [18]. Then it rewrites the text in the browser to 18.
$(document).ready(function() {
var moneyInSeats = $('#moneyInSeats');
var moneyInSeatsValue = moneyInSeats;
var moneyMultiplier = 3;
if (moneyInSeatsValue.text() != '') {
var seatsVisible = ((moneyInSeatsValue.text()) * moneyMultiplier);
var seatsPerSection = 3250;
var sectionsVisibleExact = seatsVisible / seatsPerSection;
var sectionsVisibleRounded = Math.floor(sectionsVisibleExact);
moneyInSeats.text(moneyMultiplier);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="moneyInSeats" class="hotField">20000</p>
Upvotes: 0
Views: 39
Reputation: 10935
You didn't convert the value from moneyInSeatsValue.text()
into a number.
Use this:
parseInt(moneyInSeatsValue.text(),10)
$(document).ready(function() {
var moneyInSeats = $('#moneyInSeats');
var moneyInSeatsValue = moneyInSeats;
var moneyMultiplier = 3;
if (moneyInSeatsValue.text() != '') {
var str = "moneyMultiplier: "+moneyMultiplier+'<br>';
var seatsVisible = (parseInt(moneyInSeatsValue.text(),10) * moneyMultiplier);
str += 'seatsVisible: '+seatsVisible+'<br>';
var seatsPerSection = 3250;
str += 'seatsPerSection: '+seatsPerSection+'<br>';
var sectionsVisibleExact = seatsVisible / seatsPerSection;
str += 'sectionsVisibleExact: '+sectionsVisibleExact+'<br>';
var sectionsVisibleRounded = Math.floor(sectionsVisibleExact);
str += 'sectionsVisibleRounded: '+sectionsVisibleRounded+'<br>';
moneyInSeats.html(str);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="moneyInSeats" class="hotField">20000</p>
Upvotes: 0
Reputation: 68363
Code/calculation is fine, you were printing wrong value to the UI (moneyInSeats
)
moneyInSeats.text(sectionsVisibleRounded)
Demo
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="moneyInSeats" class="hotField">20000</p>
<script>
$(document).ready(function() {
var moneyInSeats = $('#moneyInSeats');
var moneyInSeatsValue = moneyInSeats
var moneyMultiplier = 3;
if (moneyInSeatsValue.text() != '') {
var seatsVisible = ((moneyInSeatsValue.text()) *
moneyMultiplier);
var seatsPerSection = 3250;
var sectionsVisibleExact = seatsVisible / seatsPerSection;
var sectionsVisibleRounded =
Math.floor(sectionsVisibleExact)
moneyInSeats.text(sectionsVisibleRounded)
}
});
</script>
</body>
</html>
Upvotes: 2