Return Value of JavaScript function - javascript

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>

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.

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.

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>

Related

adding up numerical values ​in the table (sum)

I have number inputs
number around 30
I need to sum them all to one field
what I have is below
View:
<table>
<tbody>
<tr>
<td><input class="days_tpu" type="number" id="sth_1"></td>
</tr>
<tr>
<td><input class="days_tpu" type="number" id="sth_2"></td>
</tr>
<tr>
<td><input class="days_tpu" type="number" id="sth_3"></td>
</tr>
</tbody>
// field in which it will add up
<tfoot>
<th><input id="id_days_tpu" type="time" type="text"></th>
</tfoot>
</table>
I tried:
I try to take all inputs.
and count by length
and sum them
but, it doesn't work
Javascript:
const days_tpu_s = [...document.getElementsByClassName("days_tpu")];
//or
const table = document.querySelector('table');
table.sumInputs = function () {
var inputs = document.getElementsByClassName('days_tpu'),
result = document.getElementById('sum_id_days_tpu'),
sum = 0;
for (var i = 0; i < inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
result.value = sum;
}
sumInputs();
anyone have a good idea?
You can use Array.prototype.map() to get all the input value the use Array.prototype.reduce() to sum them.
Demo:
const days_tpu_s = [...document.getElementsByClassName("days_tpu")];
function sumInputs() {
var sum = days_tpu_s.map(i => Number(i.value)).reduce((a, c) => a + c, 0);
document.getElementById('id_days_tpu').value = sum;
}
days_tpu_s.forEach(function(el){
el.addEventListener('input', sumInputs);
});
<table>
<tbody>
<tr><td><input class="days_tpu" type="number" id="sth_1"></td></tr>
<tr><td><input class="days_tpu" type="number" id="sth_2"></td></tr>
<tr><td><input class="days_tpu" type="number" id="sth_3"></td></tr>
</tbody>
// field in which it will add up
<tfoot>
<th><input id="id_days_tpu" type="text"></th>
</tfoot>
</table>

How to sum value of checked changed checkbox jquery?

I have a table, each checkbox contains a value, and I want to sum value of the checkbox.
Example:
Candy and Water is checked : count = 2 , Candy, food and water is checked : count = 5 , checkbox is unchecked : count = 0 .
I think i must two event , event of each checkbox (.checkbox1) and event of checkbox (.check_all).
Javascript
var count = 0;
$(".checkbox1").change(function() {
var table_abc = document.getElementsByClassName("checkbox1");
for (var i = 0; table_abc[i]; ++i) {
if (table_abc[i].checked) {
count += table_abc[i].value;
}
}
});
alert(count);
HTML
<table id="div_table">
<thead>
<tr>
<th><input type="checkbox" class="check_all" id="chk_all" /></th>
<th>Check All</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox1" id="candy" value="2" /></td>
<td>Candy</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox1" id="food" value="3" /></td>
<td>Food</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox1" id="water" value="0" /></td>
<td>Water</td>
</tr>
</tbody>
</table>
But it seems not working. Can you tell me how to wrong?
here is your script, a little bit improved
i'm using here the jquery .prop() method to get the checked property of each element,
and instead of performing concatenation directly with the value of count
you have to use Number(number) or parseInt(number,base) in order to tell js engine, hey i want it to be an arithmetic operation and not a concatenation
here is your snippet of code improved :
$(document).ready(function(){
var count;
$(".checkbox1").change(function() {
count = 0;
var table_abc = $('.checkbox1');
for (var i = 0; i < table_abc.length ; ++i) {
if ($(table_abc[i]).prop('checked')) {
count += parseInt($(table_abc[i]).val(),10);
}
}
console.log(count);
});
});
we are logging to the screen the value of count each time a checkbox(with class checkbox1) state is changed
First I moved declaration of variable count inside the change function to avoid invalid value in repeating the checked-unchecked
Then you should cast the value of checkbox to a numeric so your summation gives correct values
check this fiddle, it works
Use below snippets of code
var count = 0;
$('input[type="checkbox"]').on("change", function() {
count = 0;
if($(this).hasClass('check_all')){
$('input[type="checkbox"][class="checkbox1"]').prop('checked',true);
$('input[type="checkbox"][class="checkbox1"]').each(function(){
count += parseInt($(this).val());
});
}else{
$('input[type="checkbox"]:checked').each(function(){
count += parseInt($(this).val());
});
}
alert(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="div_table" >
<thead>
<tr>
<th><input type="checkbox" class="check_all" id="chk_all" /></th>
<th>Check All</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox1" id="candy" value="2" /></td>
<td>Candy</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox1" id="food" value="3" /></td>
<td>Food</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox1" id="water" value="0" /></td>
<td>Water</td>
</tr>
</tbody>
</table>
Your javascript code seems wrong. Try following
$(document).ready(function(){
$(".checkbox1").change(function() {
var count = 0;
var table_abc = document.getElementsByClassName("checkbox1");
for (var i = 0; table_abc[i]; ++i) {
if (table_abc[i].checked) {
count += parseInt(table_abc[i].value);
}
}
alert(count);
});
});
You can easily iterate over all your checkboxes using the jquery .each function like this:
(function($){
$("input[name='opt']").change(function() {
count = 0;
$("input[name='opt']").each(function(index, checkbox){
if(checkbox.checked)
count += parseInt(checkbox.value) // convert to integer
})
alert(count);
});
})(jQuery);
Few things to pay attention to:
$("input[name='opt']").change binds all the input checkboxes with name='opt' to the provided event handler.
The count variable is moved inside the change event handler, because it needs to be reset to 0 and re-calculated everytime a checkbox is changed.
$("input[name='opt']").each(function(index, checkbox) iterates through all the input checkboxes with name='opt'.
To correctly sum the values, you will need to use parseInt to convert your string value to integer.
Instead of using class="checkbox1", I use name='opt' in my codes to group all the checkboxes together.
Check out this fiddle for complete HTML and JS codes.

Javascript not giving alert after for loop

i have a javascript function which has foor loop in it. once the loop exists it is not displaying alert can anyone suggest what might be wrong.
the code is below
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<?PHP Include('Includes\common\header_items.php');
session_start();
?>
</head>
<body>
<form name="step2" method="POST">
<div id="qwe">
<table width="500px" id="myTable" name="myTable">
<thead>
<tr>
<td >Brawing / Document No.</th>
<td>Revision No.</th>
<td>Description (Optional)</th>
</tr>
</thead>
<tbody>
<tr>
<td width="40%"><input type="text" id="553" name="2" /></th>
<td width="10%"><input type="text" id="revID553" name="3" /></th>
<td width="45%"><input type="text" id="descpID553" name="4" /></th>
</tr>
<tr>
<td width="40%"><input type="text" id="4" name="21" /></th>
<td width="10%"><input type="text" id="15" name="31" /></th>
<td width="45%"><input type="text" id="6" name="41" /></th>
</tr>
<tr>
<td width="40%"><input type="text" id="556" name="2" /></th>
<td width="10%"><input type="text" id="revID556" name="3" /></th>
<td width="45%"><input type="text" id="descpID556" name="4" /></th>
</tr>
</tbody>
</table>
<input type="submit" onclick='Javascript: return testFunc();'>
</div>
</form>
<script language="javascript">
var table_row = [];
function testFunc(){
table_row.length = 0;
var count = 0;
var testing = document.getElementById("myTable").getElementsByTagName("input");
for (i=0; i<=testing.length; i++){
var data = document.getElementById("myTable").getElementsByTagName("input")[i].id;
if(data.substring(0,2) == "55")
{
var value_doc = document.getElementById("myTable").getElementsByTagName("input")[i].value;
var value_rev = 'revID'+data;
var rev = document.getElementById(value_rev).value;
var value_descp = 'descpID'+data;
var descp_data = document.getElementById(value_descp).value;
//code to add into array
table_row[count] = [data,rev,descp_data];
count ++;
}
}
alert("I am in the end");
</script>
</body>
</html>
i cant figure out why it is not displaying the last alert. Any suggestions? THe last alert is not working.
Hello Your code is working fine for me.
Write your function like this.
function testFunc(){
alert("I am in test function");
for (i=0; i<=5; i++){
//code to add values in array
// it displays the values added in array correctly
alert('call');
}
alert("Function is Ending"); //this is not displayed once loop runs 5 times.
return true;
}
Now Call your function in load.
$(document).ready(function () {
testFunc();
});
Fiddle Demo
You have not call your function :
JSFiddle
Check Below Code :
function testFunc(){
alert("I am in test function");
for (i=0; i<=5; i++){
//code to add values in array
// it displays the values added in array correctly
}
alert("Function is Ending"); //this is not displayed once loop runs 5 times.
return true;
}
testFunc(); // calling function
The main problem is in extra loop iteration.
I also rewrite code a little bit to avoid many document.getElementById("myTable").getElementsByTagName("input"), because it causes searching over DOM every time it appears.
<script language="javascript">
var table_row = [];
function testFunc() {
table_row.length = 0;
var count = 0;
var testing = document.getElementById("myTable").getElementsByTagName("input");
for (i = 0; i < testing.length; i++) {
var data = testing[i].id;
if (data.substring(0,2) == "55") {
var value_doc = testing[i].value;
var value_rev = 'revID' + data;
var rev = document.getElementById(value_rev).value;
var value_descp = 'descpID' + data;
var descp_data = document.getElementById(value_descp).value;
//code to add into array
table_row[count] = [data, rev, descp_data];
count ++;
}
}
alert("I am in the end");
}
</script>

Sum of an checkbox list of items

I have a checkbox list of items. I want everytime I check items, to be able to display the price of the item and the sales tax for it, sum a subtotal of each value (price and tax) and sum the total cost. This is what I've done so far (the code is a mix from scripts I' ve found online):
<html>
<head>
<title>List</title>
<SCRIPT>
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i=1; i<3; i++) {
gn = 'item'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value);
}
}
document.getElementById('totalcost').value = sum.toFixed(2);
}
</SCRIPT>
</head>
<body>
<FORM >
<table border="1px" align="center">
<tr>
<td>List of Items
<td>Price
<td>Tax
</tr>
<tr>
<td><input type="checkbox" id='item1' value="10.00" onclick="UpdateCost()">item1
<td><INPUT TYPE="text" id='price1' SIZE=5 value="">
<td><INPUT TYPE="text" id='tax1' SIZE=5 value="">
</tr>
<tr>
<td><input type="checkbox" id='item2' value="15.00" onclick="UpdateCost()">item2
<td><INPUT TYPE="text" id='price2' SIZE=5 value="">
<td><INPUT TYPE="text" id='tax2' SIZE=5 value="">
</tr>
<TR>
<TD>Subtotals
<TD><INPUT TYPE="text" id="subtotal1" value="" SIZE=5>
<TD><INPUT TYPE="text" id="subtotal2" value="" SIZE=5>
</TR>
<tr>
<td>Total Cost:
<td><input type="text" id="totalcost" value="" SIZE=5>
<td><input type="reset" value="Reset">
</tr>
</table>
</FORM>
</body>
</html>
Here is a working implementation using Knockout.js. The fiddle is here: http://jsfiddle.net/pJ5Z7/.
The ViewModel and Item functions define your data structure and logic. Bindings to properties in the view-model are done in the HTML and Knockout will update those dynamically. These are two-way: I left the price values as inputs to illustrate this. If you check an item and change its price, you will see that change reflected in the rest of the model and view (after the input loses focus).
This approach allows for clean separation of concerns and much more maintainable code. Declarative bindings in Knockout and similar libraries help you avoid manual DOM manipulation as well.
If you want to change your dataset, all you have to do is add or remove items in the initialization code:
var items = [
new Item('item1', 10.00),
new Item('item2', 15.00)
];
With the old approach, you would have had to update the DOM as well as all of your logic. This data could even be loaded dynamically from a web service or anywhere else.
I also cleaned up the markup a bit and moved the size definition of input elements to CSS. It's better practice to define styles there.
If you want to learn more, just go to the Knockout website. There are a number of helpful demonstrations and tutorials.
JavaScript
//Main viewModel
function ViewModel(items) {
var self = this;
self.items = ko.observableArray(items);
self.priceSubtotal = ko.computed(function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
//Only add up selected items
items[i].selected() && (sum += parseFloat(items[i].price()));
}
return sum.toFixed(2);
});
self.taxSubtotal = ko.computed(function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
//Only add up selected items
items[i].selected() && (sum += parseFloat(items[i].taxAmount()));
}
return sum.toFixed(2);
});
self.totalCost = ko.computed(function() {
return (parseFloat(self.priceSubtotal()) + parseFloat(self.taxSubtotal())).toFixed(2);
});
//Functions
self.reset = function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
items[i].selected(false);
}
};
}
//Individual items
function Item(name, price) {
var self = this;
self.name = ko.observable(name);
self.price = ko.observable(price);
self.selected = ko.observable(false);
self.taxRate = ko.observable(0.06);
self.taxAmount = ko.computed(function() {
return (self.price() * self.taxRate()).toFixed(2);
});
}
//Initialization with data- this could come from anywhere
var items = [
new Item('item1', 10.00),
new Item('item2', 15.00)
];
//Apply the bindings
ko.applyBindings(new ViewModel(items));
HTML
<form>
<table border="1px" align="center">
<tr>
<td>List of Items</td>
<td>Price</td>
<td>Tax</td>
</tr>
<!-- ko foreach: items -->
<tr>
<td>
<input type="checkbox" data-bind="checked: selected" />
<span data-bind="text: name"></span>
</td>
<td>
<input type="text" data-bind="value: price"/>
</td>
<td>
<span data-bind="text: selected() ? taxAmount() : ''"></span>
</td>
</tr>
<!-- /ko -->
<tr>
<td>Subtotals</td>
<td>
<span data-bind="text: priceSubtotal"></span>
</td>
<td>
<span data-bind="text: taxSubtotal"></span>
</td>
</tr>
<tr>
<td>Total Cost:</td>
<td>
<span data-bind="text: totalCost"></span>
</td>
<td>
<input type="button" value="Reset" data-bind="click: reset" />
</td>
</tr>
</table>
</form>

JavaScript summing of textboxes

I could really your help! I need to sum a dynamic amount of textboxes but my JavaScript knowledge is way to week to accomplish this. Anyone could help me out? I want the function to print the sum in the p-tag named inptSum.
Here's a function and the html code:
function InputSum() {
...
}
<table id="tbl">
<tbody>
<tr>
<td align="right">
<span>June</span>
</td>
<td>
<input name="month_0" type="text" value="0" id="month_0" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>July</span>
</td>
<td>
<input name="month_1" type="text" value="0" id="month_1" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>August</span>
</td>
<td>
<input name="month_2" type="text" value="0" id="month_2" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>September</span>
</td>
<td>
<input name="month_3" type="text" value="0" id="month_3" onchange="InputSum()" />
</td>
</tr>
</tbody>
</table>
<p id="inputSum"></p>
function InputSum() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf("month_") == 0)
alert(inputs[i].value);
}
}
With a little jQuery, you could do it quite easily, using the attribute starts with selector. We then loop over them, parses their values into integers and sum them up. Something like this:
function InputSum() {
var sum = 0;
$('input[id^="month_"]').each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
}
You could even get rid of the onchange attributes on each input if you modify the code to something like this:
$(function () {
var elms = $('input[id^="month_"]');
elms.change(function() {
var sum = 0;
elms.each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
});
});
function InputSum() {
var month_0=document.getElementById("month_0").value;// get value from textbox
var month_1=document.getElementById("month_1").value;
var month_2=document.getElementById("month_2").value;
var month_3=document.getElementById("month_3").value;
// check number Can be omitted the
alert(month_0+month_1+month_2+month_3);//show result
}

Categories

Resources