javascriptdom

html script variable assignment


So I have a script block:

<script>
var totalPopulation = 0;

for(xxxxx){
  totalPopulation = totalPopulation + xxx
}
</script>


<tr>
  <input type="text" name="censusPop" value=totalPopulation/>
<tr>

I'm still quite green to javascript. But is there a way to assign the value of a variable in a script block to a HTML element like input type? I know that the code is unreachable.


Solution

  • hope it will help you to understand how javascript work

    <html>
    <head>
    <script>
        var totalPopulation = 0;
    
        function addAndShowPopulation(population) {
             totalPopulation = totalPopulation + population;
    
             var input_tag = getTag('my_input_id');
             input_tag.value = totalPopulation;
        }
    
        function startAdding() {
             addAndShowPopulation(10);
    
             setTimeout( function(){startAdding();},1000);
        }
    
        function getTag(id) {
           return document.getElementById(id);
        }
    
    </script>
    </head>
    <body onload="startAdding();">
    
    <div>
         <input type="text" id="my_input_id" name="censusPop" value="" placeholder="Total Population"/>
    
    </div>
    </body>
    </html>