0

I'm pretty new to HTML and JavaScript. I have a table, where I can click on checkboxes. A JavaScript funtion is calculating the sum of the checked boxes and gives the result in a html text field. So far so good.

Now I want to hide code or not, whether the result is lower than 2 or higher, but I don't know which value I can use to check (in the script and the html).
Which value does the function hand over? How is it called?
How can I make sum a global variable without destroying the function?

My code:

function checkTotal() {
  var sum = 0;
  document.listForm.total.value = '';

  for (i = 0; i < document.listForm.choice.length; i++) {
    if (document.listForm.choice[i].checked) {
      sum = sum + parseInt(document.listForm.choice[i].value);
    }
  }
  document.listForm.total.value = sum;
}
//alert ("Summe: " + ???);
<table>
  <form name="listForm">
    <tr>
      <td>A</td>
      <td>Inhalt 1</td>
      <td><input type="checkbox" name="choice" value="1" onchange="checkTotal()" /></td>
    </tr>
    <tr>
      <td>B</td>
      <td>Inhalt 2</td>
      <td rowspan="2" ;> <input type="checkbox" name="choice" value="1" onchange="checkTotal()" /></td>
    </tr>
    <tr>
      <td>Summe:</td>
      <td><input disabled type="text" size="2" name="total" value="0" /></td>
    </tr>
  </form>
</table>

1
  • 1
    what do you want to do? Commented Nov 20, 2020 at 18:32

3 Answers 3

2

In your javascript file, if your make a variable called total and put it outside of your method, you can then update that value every time checkTotal is run.

So:

var total;

function checkTotal() {
  var sum = 0;

  for (i = 0; i < document.listForm.choice.length; i++) {
    if (document.listForm.choice[i].checked) {
      sum = sum + parseInt(document.listForm.choice[i].value);
    }
  }

  total = sum;
}

function getTotal() {
  return total;
}

Then in your html, you can call getTotal(), which will return whatever number total is set to.

Sign up to request clarification or add additional context in comments.

2 Comments

If you clicked [<>] you could have made a snippet to show what you mean
Thanks for your help! Via alert(total); i want to put out the number, but it sais 'undefined'?
1

Which value does the function hand over?

None, Your function is not returning any value so there is no handing over anything. If you, however, want to return any value you can do so by the return statement.

ie:

function checkTotal() {
  var sum = 0;
  document.listForm.total.value = '';

  for (i = 0; i < document.listForm.choice.length; i++) {
    if (document.listForm.choice[i].checked) {
      sum = sum + parseInt(document.listForm.choice[i].value);
    }
  }
  document.listForm.total.value = sum;
  return sum;
}

So when you call the function you can save its return value

Like :

var total = checkTotal();

How is it called?

Currently its being called using event listener attribute. ie. onChange

its like doing this in javascript

document.querySelectorAll('input[type="checkbox"]')
    .forEach(function(){
        this.addEventListener("change", checkTotal)
    })

How can I make sum a global variable without destroying the function?

You just have to declare the var sum = 0; outside the function in a global scope like this

var sum = 0; 
function checkTotal() {
  sum = 0;
  document.listForm.total.value = '';

  for (i = 0; i < document.listForm.choice.length; i++) {
    if (document.listForm.choice[i].checked) {
      sum = sum + parseInt(document.listForm.choice[i].value);
    }
  }
  document.listForm.total.value = sum;
}

any function in javascript inherit the scope from its parents too so anything available before the function is declared, is also available inside the function (unlike php).

A note though: variables declared using let and const are block scoped. Meaning: they can’t be accessed from outside their immediate enclosing {...}

Putting everything together and correcting some errors

The final code looks like this.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form name="list-form">
        <table>
            <tr>
                <td>A</td>
                <td>Inhalt 1</td>
                <td><input type="checkbox" name="Inhalt_1" value="1"></td>
            </tr>
            <tr>
                <td>B</td>
                <td>Inhalt 2</td>
                <td><input type="checkbox" name="Inhalt_2" value="1"></td>
            </tr>
            <tr>
                <td>Total:</td>
                <td colspan="2"><input disabled type="text" id="total" name="total" value="0" /></td>
            </tr>
        </table>
    </form>
    <script src="path/to/your/js/file.js" type="text/javascript"></script>
</body>
</html>

JS

var checkboxes = document.forms[0].querySelectorAll('input[type="checkbox"]'),
    inpTotal = document.getElementById('total'),
    sum = 0;

// first we define the checkTotal
function checkTotal() {
    sum = 0;
    checkboxes.forEach(el => {
        if (el.checked) sum += +el.value;
    });
    inpTotal.value = sum;
    // alert(sum);
}

// then we add the event listeners
checkboxes.forEach(el => el.addEventListener("change", checkTotal));

PS: It is a good practice to put all your javascript in a seperate file from the html where possible.

2 Comments

Thanks for your detailed answer! My editor has a problem has a problem in line 4 (document.listForm.total.value = '';) with the total: ×JavaScript error: Uncaught TypeError: Cannot read property 'total' of undefined Makes sense, thanks for the explanation. I've tried that, but then the sum is always 0 in the alert-function (I use it to check which value the sum has at the moment). I've read about the different types of variables - I decided that let & const are not the ones I'm looking for - but if I define the var outside the function to make it global, it isn't working proper anymore.
@Sirona sorry, that is my bad. Your "so far so got" got me thinking the function is error free so I just blindly copy pasted in mine. Updated it.
0

Have a go at this.

I know it is a little complex but it is good practice

I fixed your illegal HTML and moved the inline event handlers to one eventListener

I gave the form an ID, using name is obsolete and not useful

If you plan to submit the form, you will need to rename one of the checkboxes or if you use PHP on the server, add [] to the name to make an array

Here I renamed them and gave them a class to use for the selector

document.getElementById("listForm").addEventListener("input", function() {
  let sum = 0;
  const checked = [...this.querySelectorAll(".choice:checked")].map(inp => +inp.value); // get all values from checked and convert to number
  if (checked.length > 0) sum = checked.reduce((a, b) => a + b); // sum them
  console.log(sum)
  document.getElementById("total").value = sum; // show value
  document.getElementById("showwhen2").classList.toggle("hide", sum < 2); // unhide when >= 2
});
.hide {
  display: none;
}
<form id="listForm">
  <table>
    <tbody>
      <tr id="A" +>
        <td>A</td>
        <td>Inhalt 1</td>
        <td><input type="checkbox" class="choice" name="choiceA" value="1" /></td>
      </tr>
      <tr>
        <td id="B">B</td>
        <td>Inhalt 2</td>
        <td><input type="checkbox" class="choice" name="choiceB" value="1" /></td>
      </tr>
      <tr>
        <td>Summe:</td>
        <td><input disabled type="text" size="2" name="total" id="total" value="0" /></td>
      </tr>
    </tbody>
  </table>
</form>

<div id="showwhen2" class="hide">Equal 2</div>

7 Comments

Just curious, don’t we need to cast the value to int?
@MohamedMufeed I am, here: => +inp.value
@mplungjan what is than syntax called? I have never seen it before. I googled it but can’t search well
@MohamedMufeed Unary plus
Another question: Do you recommend any lecture for JavaScript beginners? I'm familar with Java and C, I've also learned HTML (and CSS) and now I want to dive in the world of JavaScript!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.