JavaScript summing of textboxes - javascript

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
}

Related

Javascript check boxes based on text in rows

I am trying to convert this: Select table row and check checkbox using JQuery
into normal javascript, since I'm in a situation where I cannot use jquery.
Here is the orignal
$("table tr").each(function () {
if ($(this).find("td:eq(1)").text().trim() == '2013-03-21') {
$(this).find("input[type=checkbox]").attr("checked", true);
}
});
This is what I have so far, and I'm sure its way off:
var elements = [].slice.call(document.querySelectorAll("table tr"));
Array.prototype.forEach(elements, function(){
var tdText = this.querySelectorAll("td").textContent
if (tdText == '2013-03-21') {
this.querySelectorAll("input[type=checkbox]").setAttribute("checked", true);
}
});
This is the original table:
<table>
<tr>
<td>Record1</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record2</td>
<td>2013-03-22</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record3</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>
querySelectorAll() returns a nodeList of elements.
You need to iterate those and deal with each instance or use the index you want like:
element.querySelectorAll("td")[0]
The code var tdText = this.querySelectorAll("td").textContent will return an undefined textContent because you are referring to the tr's NodeList. You can loop through it and then you can get the td's content:
let rows = Array.prototype.slice.call(document.querySelectorAll('table tr'));
let textDate = '2013-03-21';
rows.map((row) => {
let cells = Array.prototype.slice.call(row.querySelectorAll('td'));
for (let i = 0, length = cells.length; i < length; i++) {
if (cells[i].textContent === textDate) {
let cb = row.querySelectorAll('input[type=checkbox]');
cb[0].checked = true;
return;
}
}
});
Use ElemCollection.forEach.call instead of using Array#slice.call as HTMLCollection does not have forEach method
Use [1] index while selecting text from td element
this in Array#forEach does not refer to element, use first argument of Array#forEach callback function which is item of array
Array.prototype.forEach.call(document.querySelectorAll("table tr"), function(elem) {
var tdText = elem.querySelectorAll("td")[1].textContent;
if (tdText === '2013-03-21') {
elem.querySelector("input[type=checkbox]").setAttribute("checked", true);
}
});
<table>
<tr>
<td>Record1</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record2</td>
<td>2013-03-22</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record3</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>

How to read an array of integers from an element to get values from it?

I make a code , that randomly display an 6-item array in a div.
i want to read the array and pass it to function to calculate the mean of it?
HTML
what i must do , how can i store the data of div(id="numbers" )
and push it in array ?
<pre>
<div >
<form action="" method="post" name="meanForm" onsubmit='return false' id="formmine">
<table width="100%" border="0"
<tr>
<td colspan="3" style="background-color:#06F ;color:#FFF">Answer this problem</td>
</tr>
<tr>
<td style="color:green; font-size:20px">What is the mean of these numbers </td>
<td colspan="2" ><div id="numbers"></div>
</td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr id="answerANDpic">
<td height="62" colspan="3" align="center" > <input name="" type="text" size="15" maxlength="100" height="50" style=" border: solid #0C0 ; border-width:thin" id="answer" onkeydown="searchm(this)"/> </td>
</tr>
<tr>
<td colspan="3" ><div id ="explain" ></div></td>
</tr>
<tr>
<td> </td>
<td><input name="" type="button" id="newEx" style="background-color:green ; color:white" align ="left" value="New Problem" class="send_feed" onclick="randomArray(6,0,99)" /></td>
<td><input name="" type="button" id="solution" style="background-color:#606 ; color:#FFF " align="left" class="send_feed" value="Solution" onclick="solution()"/></td>
</tr>
</table>
</form>
</div>
in JS
var myNumArray = randomArray(6,0,99);
function random_number(min,max) {
return (Math.round((max-min) * Math.random() + min));
}
function randomArray(num_elements,min,max) {
var nums = new Array;
for (var element=0; element<num_elements; element++) {
nums[element] = random_number(min,max);
}
document.getElementById("numbers").innerHTML=nums;
calcMean(nums);
}
function calcMean(nums) {
var num=0;
for (var i=0;i<nums.length;i++) {
num += parseFloat( nums[i], 6 );
}
var divide=num/nums.length;
var mean=(parseInt(divide,10));
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
return mean,maxi,mini;
}
function searchm(ele) {
if(event.keyCode == 13) {
// alert(ele.value); // i get the value and put it on alert
var inans= ele.value;
return inans;
}
}
function soltuion(){
//read array saved in div id="numbers"
// call calcMean()
//get the mean and max min values
}
See comments in code below. Your code is not far off working.
function calcMean(nums){
var num=0;
for (var i=0;i<nums.length;i++){
// parseFloat only has one argument
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
num += parseFloat( nums[i])
// If the numbers in the nums array
// are already floats, you don't need parseFloat
// So maybe you can do... ?
// num += nums[i]
}
// The line below might divide by zero, so check
if (nums.length == 0) {
return 0;
}
var divide=num/nums.length;
// No need to reparse a number.
mean=divide
// This code suggests that nums is already filled with numbers
// See comment in for-loop above
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
// This returns all 3 numbers
return [mean,mini,maxi];
// If you want just the mean,
// return mean;
}

Iterating through table and get the value of a button in each tablerow jQuery

I have buttons in a table which are created dynamically. I want to iterate through a table, get the tablerows which contain a checked checkbox and get the value of a button inside the tablerow. I want to push the values in an array after. The buttons don't have a unique ID so I cannot get their values by id.
I tried to get the values through giving the buttons a class and itering works fine but the array is filled with empty entries.
$("#bt_multiple_deletion").off().on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).find(".filefolder-button").text());
});
})
I really don't know what Im doing wrong. I tried to get the values with .text(), .val() etc.
My table row looks like this:
<tr class="select">
<td>
<span class="countEntries"><input id="lv_fifo_ctrl7_cb_delete_file" type="checkbox" name="lv_fifo$ctrl7$cb_delete_file" /></span>
</td>
<td>
<img src="images/icons/013_document_02_rgb.png" alt="document" />
</td>
<td class="name">//the button i want to get the value from
<input type="submit" name="lv_fifo$ctrl7$bt_file" value="013_document_png.zip" id="lv_fifo_ctrl7_bt_file" class="filefolder-button download file del" style="vertical-align: central" />
</td>
<td>
<span id="lv_fifo_ctrl7_lb_length">33.14 KB</span>
</td>
<td>
<span id="lv_fifo_ctrl7_lb_CreationTime">21.10.2014 07:34:46</span>
</td>
<td></td>
<td>
<input type="submit" name="lv_fifo$ctrl7$bt_del_file" value="delete" id="lv_fifo_ctrl7_bt_del_file" class="delete-button delete-file" />
</td>
</tr>
The problem is rows is the input elements not the tr elements so in the loop you need to find the tr which contains the input then find the target element inside it
$("#bt_multiple_deletion").off().on("click", function () {
var checked = $(".select").find("input[type=checkbox]:checked");
var files = checked.map(function () {
return $(this).closest('tr').find(".filefolder-button").val();
}).get();
})
Another option is
$("#bt_multiple_deletion").off().on("click", function () {
var rows = $(".select").find("tr").has('input[type=checkbox]:checked');
//var rows = $(".select").find('input[type=checkbox]:checked').closest('tr');
var files = rows.map(function () {
return $(this).find(".filefolder-button").val();
}).get();
})
#Timo Jokinen Do you need this
$("#bt_multiple_deletion").on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).parents("tr").find("td.filefolder-button").text());
});
console.log(files);
})
<table class="select">
<tr>
<td class="filefolder-button">test1</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test2</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test3</td>
<td><input type="checkbox" /></td>
</tr>
</table>
<button id="bt_multiple_deletion">delete</button>
Checkout example link here

JavaScript - HTML5 data attributes

I've looked around on the web for an answer to my question. Found lots of scripts that I've copied and messed around with but can't get it working properly.
When I run it, my script below initially works but then displays 'NaN'.
I'm trying to create a simple order form that uses JavaScript to dynamically update and display the order total.
Each item for sale has an input (type=number) tag that contains the item's price in a 'data-price' attribute.
What I'm trying to do is grab the price out of the data-price attribute and use it in a JS script to display a total.
Users can enter a quantity into text field and the TOTAL text field should automatically update with correct 'running total'.
Would appreciate any advice as to where I'm going wrong. I've used JavaScript (as opposed to jQuery) because I'm more familiar with the syntax.
<script>
function calculateTotal(frm) {
var order_total = 0
for (var i=0; i < frm.elements.length; ++i) {
form_field = frm.elements[i];
item_price = form_field.dataset.pric);
item_quantity = form_field.value;
if (item_quantity >= 0) {
order_total += item_quantity * item_price;
}
}
frm.total.value = round_decimals(order_total, 2);
}
function round_decimals(original_number, decimals) {
var result1 = original_number * Math.pow(10, decimals);
var result2 = Math.round(result1);
var result3 = result2 / Math.pow(10, decimals);
return result3.toFixed(2);
}
</script>
</head>
<body>
<form id="order-form">
<table cellpadding="8" align="center">
<tr>
<td align="left" width="150">Image</td>
<td align="left">Description</td>
<td align="left">Price</td>
<td align="left">Quantity</td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left">Poster</td>
<td align="left">$24.00</td>
<td align="left"><input type="number" data-price="24" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left"> T-shirt</td>
<td align="left">$66.00</td>
<td align="left"><input type="number" data-price="65" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left"> Bag</td>
<td align="left">$120.00</td>
<td align="left"><input type="number" data-price="120" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td></td>
<td></td>
<td>TOTAL:</td>
<td align="right"><input type="text" name="total" size="6" onFocus="this.form.elements[0].focus()"></td>
</tr>
</table>
</form>
</div>
You have a typo in the sample code.
item_price = form_field.dataset.pric);
should probably be
item_price = form_field.dataset.price;
Apart from that, NaN is caused by the fact that you're also taking into account the value of the 'total' field when you run the function calculateTotal(). But that field does not have a data-price attribute so you're multiplying undefined with a number, resulting in NaN.
You need to add an extra check if there is a 'data-price' attribute:
function calculateTotal(frm) {
var order_total = 0;
for (var i=0; i < frm.elements.length; ++i) {
form_field = frm.elements[i];
if(typeof(form_field.dataset.price) != 'undefined') {
item_price = form_field.dataset.price;
item_quantity = form_field.value;
if (item_quantity >= 0) {
order_total += item_quantity * item_price;
}
}
}
frm.total.value = round_decimals(order_total, 2);
}

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>

Categories

Resources