Sirona
Sirona

Reputation: 5

Return Value of JavaScript function

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>

Upvotes: 0

Views: 160

Answers (3)

mplungjan
mplungjan

Reputation: 177702

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>

Upvotes: 0

Mohamed Mufeed
Mohamed Mufeed

Reputation: 1560

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.

Upvotes: 1

Jamie G
Jamie G

Reputation: 186

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.

Upvotes: 2

Related Questions