Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a span value into a javascript variable

I am trying to write javascript that will go through a span, grab its value, and store it in a variable that can be used to perform arithmetic.

<span id ="Weekly" class="ServerData" data-tag="WeeklyCarSales">**30**</span>
<span id ="Monthly" class="ServerData" data-tag="DailyCarSales">**6**</span>

Pertaining to the above two lines, my function is given below. In this current set up I get no result.

function divide(n1, n2) {
    ans = n1 / n2;
    document.write(" " + ans + "<BR>");
    return ans;
}
var a = $('#WeeklyCarSales').ServerData;
var b = $('#DailyCarSales').ServerData;
divide(a, b);

I should be getting an answer of "5" yet get nothing. I know the actual arithmetic works if I force an integer/float value into the variables. I seem to have continuous trouble locking down the the '30' and '6', which are the span values. Any ideas on how to grab those 2 span values?

like image 810
J.C.Morris Avatar asked Dec 20 '22 18:12

J.C.Morris


1 Answers

This should do the trick...

function divide(n1, n2) {
    var ans = n1 / n2;
    document.write(" " + ans + "<BR>");
    return ans;
}

var a = parseInt($("#Weekly.ServerData").text().replace(/\*/gmi, ""), 10)
  , b = parseInt($("#Monthly.ServerData").text().replace(/\*/gmi, ""), 10);

divide(a, b);

​​Here is working JSFiddle

like image 93
Split Your Infinity Avatar answered Dec 31 '22 05:12

Split Your Infinity