Sarah Boss
Sarah Boss

Reputation: 41

javascript multiple loops

I am trying to get the sum of a list of words displayed in an HTML browser.

If each word is assigned a number i.e

a is 1, b is 2

and so on upto z is 26, then the sum of apple should be 50. I want them to be displayed in browser like below:

apple  
carrot
money  

50
75
72

but I am not able to get the loop to work correctly.

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
   function newSquare(){
      for(var j=0; j<10; j++){
         calcAlpha(j);
      }
   }
   function newDisplay(){
      for(var k=0; k<10; k++){
         calcAlpha(k);
      }
   }
   function calcAlpha() {
      var word = document.getElementById("square + j").childNodes[0].data;
      var sum = 0;
      for(var i=word.length-1; i>=0; i--) {
         sum += (word.charCodeAt(i) - 96);
      }
      document.getElementById("display + k").innerHTML=sum
   }
</script>
</head>
<body>
   <h1>Calculate sum of words</h1>
   <table>
      <tr><td id="square1">apple</td></tr>
      <tr><td id="square2">carrot</td></tr>
      <tr><td id="square3">money</td></tr>
      <tr><td id="square4">game</td></tr>
   </table>
   <table>
      <tr><td id="display1">&nbsp;</td></tr>
      <tr><td id="display2">&nbsp;</td></tr>
      <tr><td id="display3">&nbsp;</td></tr>
      <tr><td id="display4">&nbsp;</td></tr>
   </table>
   <div id="display"></div>
   <button onclick="calcAlpha()">calculate</button>
</body>
</html>

Can someone can sort this for me? I am still a beginner at Javascript, and I dont understand how to put i,j, and k in loops. Thanks.

Upvotes: 2

Views: 8028

Answers (4)

Peter-Paul van Gemerden
Peter-Paul van Gemerden

Reputation: 7011

The first problem, like Michael said, is this:

document.getElementById("square + j")
// and
document.getElementById("display + k")

This will look for the element whose id exactly matches "square + j" or "display + k". To concatenate the value of a variable to a string, use "square" + j and "display" + k.

The second problem is that in the context of calcAlpha, the variables j and k are undefined. You can fix this by either making them accessible to calcAlpha (by defining them outside the scope of function calcAlpha) or by passing j (or k) as a parameter. You're already doing the first part of that (actually passing it along). All you need now is to use it in the declaration of calcAlpha, like so:

function calcAlpha(index) {
  var word = document.getElementById("square" + index).childNodes[0].data;
  // [...]
}

The variable index will now contain the value of the j or k you passed along.

One other thing: you're calling calcAlpha both from the other functions and from the <button>'s onclick. That's probably not what you want to do. Have a look at Bergi's answer, his/her solution should solve your problem.

Upvotes: 0

laker
laker

Reputation: 599

Here's a complete answer:

There are three main problems with the code. First, i, j, and k are var's with specific integer values in this example. "square + j" is just a string that does not have the desired values (i.e. square1, square2, etc.). As Michael has suggested, you should put "square" + j.

The second issue is that the only function to run in your webpage is calcAlpha(), which you call in the onclick event of the button element. Within calcaAlpha() you never call newSquare() or newDisplay(), so they never execute.

The third issue is the namespace, or scope of your javascript variables. Within calcAlpha() you cannot access the variables j or k because they are declared in external functions that don't encapsulate the calcAlpha() function. However, you can access the variable i because it is declared in calcAlpha().

The solution to your problem would be to remove newDisplay() and newSquare() and change calcAlpha() to something like this:

function calcAlpha() {
    for (var j = 1; j <= 4; j++) {
        var word = document.getElementById("square" + j).childNodes[0].data;
        var sum = 0;
        for(var i=word.length-1; i>=0; i--) {
            sum += (word.charCodeAt(i) - 96);
        }
        document.getElementById("display" + j).innerHTML=sum

    }
}

This is basically the combined code for newSquare() and newDisplay() which is put into calcAlpha() and fixed for the other issues described above. Notice that the variable k is unnecessary because you want to put the numeric sum of squareN into displayN, so you can use a single variable, j.

Upvotes: 2

Bergi
Bergi

Reputation: 664256

I'm not sure what you want to do with those functions, but try this:

function run() {
// reads, calculates and prints all words
    for (var i=1; i<=4; i++) {
        var word = document.getElementById("square"+i).childNodes[0].data;
        var result = calcAlpha(word);
        document.getElementById("display"+i).childNodes[0].data = result;
    }
}
function calcAlpha(text) {
   text = text.toLowerCase();
   var sum = 0;
   for (var i=text.length-1; i>=0; i--) {
       sum += text.charCodeAt(i) - 96;
   }
   return sum;
}

And call the run function from the button.

Upvotes: 1

MikeB
MikeB

Reputation: 2452

One thing I saw that you did incorrectly right away was getting the element by id. You were including the looping variable as a string instead of an int. Here is my solution:

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">

   function calcAlpha()
   {
        for(j =1; j<=4; j++)
        {
            var word = document.getElementById("square" + j).innerHTML;
            var sum = 0;
            for(var i=word.length-1; i>=0; i--) 
            {
                sum += (word.charCodeAt(i) - 96);
            }
            document.getElementById("display" + j).innerHTML=sum
        }
   }

</script>
</head>
<body>
   <h1>Calculate sum of words</h1>
   <table>
      <tr><td id="square1">apple</td></tr>
      <tr><td id="square2">carrot</td></tr>
      <tr><td id="square3">money</td></tr>
      <tr><td id="square4">game</td></tr>
   </table>
   <table>
      <tr><td id="display1">&nbsp;</td></tr>
      <tr><td id="display2">&nbsp;</td></tr>
      <tr><td id="display3">&nbsp;</td></tr>
      <tr><td id="display4">&nbsp;</td></tr>
   </table>
   <div id="display"></div>
   <button onclick="calcAlpha()">calculate</button>
</body>
</html>

Upvotes: 0

Related Questions