Click here to Skip to main content
14,494,314 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am mainly a VB guy but recently working on a HTML/JS project.Im getting a little confused on how to reference JS variables in HTML.

My HTML code(index.html):
<div class="box4 boxes">
  <div class="centered addPadding">
    Total Recovered
    <div id="totalRecovered" class="bigGreenNumber">...</div>
    <p1 id="recPerc"></p1>
  </div>
</div>
<script src="index.js"></script>
My JS Code(index.js):
function percentageRecovered(recPerc) {    
  var tr = document.getElementById("totalRecovered").innerHTML;
  var tc = document.getElementById("totalConfirmed").innerHTML;
  var recPercentage = (tr / tc) * 100;
  document.getElementById("recPerc").innerHTML = "Percentage: " + tc;
  return recPerc;
}


What I have tried:

I tried using a few only resources but I still come up with the same results. If I were to paste my function directly into my HTML document using:
<script>
  var tr = document.getElementById("totalRecovered").innerHTML;
  var tc = document.getElementById("totalConfirmed").innerHTML;
  var recPercentage = (tr / tc) * 100;
  document.getElementById("recPerc").innerHTML = "Percentage: " + tc;
</script>
I get my "Percentage:" to show up but the problem is that my variables (totalRecovered, totalConfirmed) are in the JS document so i dont get the proper result.
Posted
Updated 25-Mar-20 23:13pm
v3
Comments
MadMyche 25-Mar-20 15:57pm
   
What result do you get?
ZurdoDev 25-Mar-20 16:30pm
   
What are you wanting to do?
gggustafson 25-Mar-20 16:35pm
   
Normally JavaScript is referenced as the target of an event (thus known as an event handler). Place a button in your HTML and use an attribute something like "onclick='percentageRecovered()'". By the way, I know of no HTML tag named "<p1>" do you mean "<p>"

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

You have your code in a function called percentageRecovered but you're not doing anything to call it. It also has a param you don't need. So either update your js

function percentageRecovered() {    
  var tr = document.getElementById("totalRecovered").innerHTML;
  var tc = document.getElementById("totalConfirmed").innerHTML;
  var recPercentage = (tr / tc) * 100;
  document.getElementById("recPerc").innerHTML = "Percentage: " + tc;
}


and your html

<script src="index.js"></script>
<script>percentageRecovered();</script>


Or just remove the function from your js so it has only the code

var tr = document.getElementById("totalRecovered").innerHTML;
var tc = document.getElementById("totalConfirmed").innerHTML;
var recPercentage = (tr / tc) * 100;
document.getElementById("recPerc").innerHTML = "Percentage: " + tc;
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100