Get a value and do the maths based on that value - javascript

I am doing an odds comparison site, What I'd like to do is get the value i.e 13/2 and do the maths as in 13 Divided 2 = 6.5
Then I'd like to tag the 6.5 on as a data-odds-decimal value on a button.
My jQuery is looping each class, But not doing the necessary maths.
My HTML code is as follows :
<button class="odds-btn" data-odds-fractional="13/2">13/2</button>
<button class="odds-btn" data-odds-fractional="2/5">2/5</button>
<button class="odds-btn" data-odds-fractional="1/2">1/2</button>
So for each data-odds-fractional I need to do the maths of 13/2, 2/5, 1/2 to then return the decimal value.
My current jQuery is as follows...
$('.odds-btn').each(function()
{
// Get The Decimal Value...
var odds_decimal = $(this).attr('data-odds-fractional');
// Add The Fractional Value as a new attr...
var odds_fractional = odds_decimal;
$(this).attr('data-odds-decimal', odds_fractional);
})
The data-odds-decimal is just coming back as the fractional value, Can I get jQuery to force do the maths or any other way?
Cheers

You can't make jQuery do a calculation like that, it will only do simple parsing when reading the data values.
Split the string and do the calculation:
var parts = odds_decimal.split('/');
var odds_fractional = parseInt(parts[0], 10) / parseInt(parts[1], 10);

Related

How to use JavaScript to replace an attribute inside a span tag?

I'm looking to update the data-value attribute's value in the code below with a dynamic integer value I will return in a small JS code I wrote. My code will generate a different integer based on a few factors that vary day to day, but in any case, it returns one single integer value that I want to insert into the data-value attribute.
I have a current solution that works but is "ugly" I think. I basically used DOM manipulation to hide the value the code below produces in the UI, and implemented my own counter from 0 to the dynamic integer value. Is there a more direct and "proper" way of solving the problem, something like innerHTML but maybe for attributes? Thanks!
<div class="content-box-percentage content-box-counter" style="color:#ffffff;font-size:60px;line-height:normal;">
<i class="counter-box-icon fontawesome-icon fa-mug-hot fas" style="font-size:70px;" aria-hidden="true"></i>
<span class="display-counter" data-value="21" data-direction="up" data-decimals="0">0</span>
</div>
Thanks
EDIT: adding the "ugly" code I had, as requested. Originally I had the class ID bsa-counter in the first code snippet. As I was looking to make it prettier (therefore the reason for my post in the first place), I removed the class ID and the JS code as I was planning on starting over.
"use strict";
// CounterBox multiplier - multiplies the number of days by an integer
const bsaMultiplier = 3;
// Customize counter boxes to support counting from a start date to the current date, in number of days
// Run custom counter box function, passing in bsaMultiplier
bsaCounterBoxToToday(bsaMultiplier);
function bsaCounterBoxToToday(bsaMultiplier) {
const bsaStartDateC = "2019/07/14"; // enter in the format of "YYYY/MM/DD", including quotes
const bsaDomElementId = "bsa-counter"; // DOM ID element to select
const bsaDomElementClass = "display-counter"; // DOM Class element to select
const bsaCounterDuration = 500;
// Date range
const bsaStartDate = new Date(bsaStartDateC);
const bsaToday = new Date(
`${new Date().getFullYear()}/${
new Date().getMonth() + 1
}/${new Date().getDate()}`
);
// Days * multiplier
const bsaCountToValue =
Math.ceil(Math.abs(bsaToday - bsaStartDate) / (1000 * 60 * 60 * 24)) *
bsaMultiplier;
let bsaCurrentValue = 0;
let bsaIncrSpeed = setInterval(() => {
bsaCurrentValue < bsaCountToValue
? (document
.getElementById(bsaDomElementId)
.getElementsByClassName(bsaDomElementClass)[0].textContent =
++bsaCurrentValue)
: clearInterval(bsaIncrSpeed);
}, bsaCounterDuration / 100);
}
I think this might be what you're looking for:
var yourInt = 4;
document.getElementsByClassName("display-counter")[0].setAttribute("data-value", parseInt(yourInt));
There are multiple ways of getting the span element's DOM, but this is one way if your span element is first on your html doc. Consider using an id and the "getElementById()" function instead:
document.getElementById("the-id-name-you-added").setAttribute("data-value", parseInt(yourInt));
change your span to be:
<span id="the-id-name-you-added" class="display-counter" data-value="21" data-direction="up" data-decimals="0">0</span>

Subtract 1 from variable jQuery

Having some trouble getting this right. I'm very new to jQuery, so trying to get better and learn.
Currently I am getting 2 different values from a html table using the following code
var sellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var buyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
These both output a value such as $13,000,000
I am then wanting to subtract 1 from these values (making it $12,999,999) before pasting them to an input as such
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
However, I am having some trouble with how to subtract $1 from these.
I tried using sellPrice--; but without success.
I've also tried adding - 1; at the end of each variable, but did not succeed either.
I tried to test something like this, but did not work either.
var minusOne = -1;
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = (getCurrentSellPrice - minusOne);
var buyPrice = (getCurrentBuyPrice - minusOne);
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);`
Trying my best to familiarize myself with jQuery :)
Any help is much appreciated!
Solved using this
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = Number(getCurrentSellPrice.replace(/[^0-9\.]+/g,"")) - 1;
var buyPrice = Number(getCurrentBuyPrice.replace(/[^0-9\.]+/g,"")) + 1;
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
Since your numbers contain currency symbol and are strings, you need to convert them to proper numbers before subtracting them. See the answer below.
How to convert a currency string to a double with jQuery or Javascript?

Javascript ParseFloat to autofill without decimals

I have some inputs in a HTML form using javascript to autofill the inputs on changes
The problem is that the follow code show decimals longer decimals like this 42880.34623465464356435634 The code is:
thetotal.value = parseFloat(total.value) * (1.00/1.19);
This code get the price less taxes from the total and it works, but it show me the decimals...
What I need is the price to be in the example:
42880
Without dots or commas . or , like 42.880 or 42,880 and absolutly not 42880.34623465464356435634
I only want to show 42880
Tried with .round like this:
thetotal.value = parseFloat(total.value) * (1.00/1.19).round(2);
.round(2) but for some reason the addEventListener stop working for this input when using .round(2)
user parseInt function for it. Like below :
thetotal.value = parseInt(parseFloat(total.value) * (1.00/1.19));
You will get only Integer as output.
Another way is Math.round. Like it below :
thetotal.value = Math.round(parseFloat(total.value) * (1.00/1.19));
why don't you use Math.round()?
var total = {};
total.value = 51027.6120192;
var thetotal = {};
thetotal.value = Math.round(parseFloat(total.value) * (1.00/1.19));
document.write(thetotal.value);
Output
42880

Trying to understand how to use parseFloat to convert string to number

I'm trying to understand how to user parseFloat to convert a string to a number--which by the way changes based on a users rewards club points.
Here's the code I've written so far:
var ptsBalance = jQuery('.value.large.withCommas').text(); // get current RC points balance
var strParse = parseInt(ptsBalance, 10); // * Output should be current RC balance
alert(strParse); // alert Rewards Club Balance
var bonusPoints = 70000;
var totalPts = jQuery(strParse + bonusPoints); // sum total of Bonus and Current points
jQuery(strParse).appendTo('.currentPts');
jQuery(totalPts).appendTo('.totalPts'); // insert RC points balance after 'Current Points' text
Clearly I'm not using pareFloat, but rather strParse, which is rounding my string. That said, how do I convert a string to a number that could be "10", "100", "1,000", "10,000" etc.?
Here's a link to my Fiddle: http://jsfiddle.net/bkmills1/60vdfykq/
Still learning...
Thanks in advance!
In your fiddle, change line 4 from:
var strParse = parseInt(ptsBalance, 10);
to
var strParse = parseInt(ptsBalance.replace(',',''), 10);
You may also want to remove any other symbols needed, or even use regular expressions to do just that.

2 text box need to verify they are not empty or contain 0

I have a function with info that grabs hours, rates, and then tax deduction and then spits it out. It works fine
var newtax= new Number(dep[i]);
taxrate = newtax*100;
var h=eval(document.paycheck.hours.value);
var r=eval(document.paycheck.payrate.value);
document.paycheck.feedback.value= taxrate + txt;
var total= r*(1-newtax)*h ;
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
I have to put where it takes the total and puts it in a function to put it only two decimals. It works this way and only does two decimals but i need the decimal conversion in a function. can anyone shed some like .
This is where i cut it to two decimals and i am unable to put in function and then send it back to the feedback3.value.
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
If you're asking how to write a function that takes a number and formats it as a dollar value with two decimals (as a string) then this would work:
function formatMoney(num) {
return "$ " + num.toFixed(2);
}
// which you could use like this:
document.paycheck.feedback3.value= formatMoney(total);
// though you don't need the total variable (unless you use it elsewhere)
// because the following will also work:
document.paycheck.feedback3.value = formatMoney( r*(1-newtax)*h );
By the way, you don't need eval to get the values from your fields. Just say:
var h = document.paycheck.hours.value;
var r = document.paycheck.payrate.value;

Categories