In the HTML below, I want to simply divide two numbers and return the result to the page. The javascript accomplishes this, however, the variable A (GAL2_G2rAimTonsPerHr) is updated every 10 seconds or so from our PI server (historian). How can I set the variable A to equal the changing value? Is there a way I can store it in a temporary variable to be used as a divisor in the script?
< td align="left" style="font-size: 12px" width="60px"
< span class='PIData' data-tag='GAL2_G2rAimTonsPerHr' data-on_pi_change='truncReading' >< /span>
< /td>
<SCRIPT LANGUAGE="JavaScript">
function divide(n1,n2)
{
ans = n1/n2;
document.write(" "+ans+"<BR>");
return ans;
}
var a = 'GAL2_G2rAimTonsPerHr'????;
var b = 2;
divide(a,b);
</SCRIPT>
You've said the actual element will get updated by PI-Plug. If so, and it's really a number, then:
var value = parseInt($(".PIData[data-tag]").attr("data-tag"), 10);
The .PIData[data-tag]
part is a CSS-style selector for an element with class="PIData"
and a data-tag
attribute. Then the rest is getting the value of that attribute and parsing it into a decimal number (as it will be a string, e.g. "300"
rather than 300
).
Or instead of attr
you can use data
and leave off the data-
part of the attribute name:
var value = parseInt($(".PIData[data-tag]").data("tag"), 10);
I don't do that because I don't like the fact that the data
function is asymmetrical (it reads from data-*
attributes but doesn't write to them), but it would work fine for what you're doing.
A good read through the jQuery API documentat would be a good idea. It literally only takes about an hour, and it repays you very, very quickly indeed.