Parsing input without requiring button press with Javascript - javascript

I am currently looking for a solution to add some user-typed numbers instantly/automatically without having to click on any button. For now, I have a table asking the user for the numbers and displaying the result after the user clicked on the "Total" button. I would like to get rid of that button and that the "Total" row of the table automatically refresh to the new total, every time the user changes a value.
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
<style>
body {
width: 100%;
height: 650px;
}
#rent, #food, #entertainment, #transportation, #total {
height: 30px;
font-size: 14pt;
}
</style>
</head>
<body>
<center>
<h1></h1>
<script type="text/javascript">
function CalcTotal() {
var total = 0;
var rent = +document.getElementById("rent").value;
var food = +document.getElementById("food").value;
var entertainment = +document.getElementById("entertainment").value;
var transportation = +document.getElementById("transportation").value;
var total = rent + food + entertainment + transportation;
document.getElementById("total").innerHTML = total;
}
</script>
<table border="1">
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>Rent</td><td><input type="text" id="rent"></td>
</tr>
<tr>
<td>Food</td><td><input type="text" id="food"></td>
</tr>
<tr>
<td>Entertainment</td><td><input type="text" id="entertainment"></td>
</tr>
<tr>
<td>Transportation</td><td><input type="text" id="transportation"> </td>
</tr>
<tr>
<td>Total</td><td><div id="total"></div></td>
</tr>
</table>
<input type="submit" value="Total" onclick="CalcTotal()" id="total">
</center>
</body>
</html>

Add a keyup listener to every input field:
function CalcTotal() {
var total = 0;
var rent = +document.getElementById("rent").value;
var food = +document.getElementById("food").value;
var entertainment = +document.getElementById("entertainment").value;
var transportation = +document.getElementById("transportation").value;
var total = rent + food + entertainment + transportation;
document.getElementById("total").innerHTML = total;
}
document.querySelectorAll('input[type="text"]')
.forEach(input => input.addEventListener('keyup', CalcTotal));
body {
width: 100%;
height: 250px;
}
#rent,
#food,
#entertainment,
#transportation,
#total {
height: 30px;
font-size: 14pt;
}
<table border="1">
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>Rent</td>
<td><input type="text" id="rent"></td>
</tr>
<tr>
<td>Food</td>
<td><input type="text" id="food"></td>
</tr>
<tr>
<td>Entertainment</td>
<td><input type="text" id="entertainment"></td>
</tr>
<tr>
<td>Transportation</td>
<td><input type="text" id="transportation"> </td>
</tr>
<tr>
<td>Total</td>
<td>
<div id="total"></div>
</td>
</tr>
</table>
<input type="submit" value="Total" onclick="CalcTotal()" id="total">
Note that NodeList.forEach is somewhat new - if you have to support old browsers, you'll have to use a polyfill, or iterate over the inputs some other way instead. For example:
Array.prototype.forEach.call(
document.querySelectorAll('input[type="text"]'),
input => input.addEventListener('keyup', CalcTotal)
);

Related

HTML table filter with unique values only

I have a 300x11(rowXcolumn) html table that I wanted to filter exactly like Excel or Google Sheets's filter. However, after searching a bit I found out the following code below in a website. This works as I wanted but it has one major problem. It shows same value multiple times. For example in the 2nd column, there are 2 values same "Apple" and 2 whitespaces . In the current code, it displays Apple twice and whitespace twice. However, I want it should show the same values only once. For example, it will show "Apple" only once, and if I select apple it will filter both rows containing apple.
Thank you very much for your help.
index.html
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.0.3" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<table class="grid">
<thead>
<tr>
<td index=0>Name
<div class="filter"></div>
</td>
<td index=1>Address
<div class="filter"></div>
</td>
<td index=2>City
<div class="filter"></div>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>first</td>
<td>first add</td>
<td>SDF dfd</td>
</tr>
<tr>
<td>second</td>
<td></td>
<td>SDF dfd</td>
</tr>
<tr>
<td>third</td>
<td>Apple</td>
<td>SDF dfd</td>
</tr>
<tr>
<td>third</td>
<td></td>
<td>SDF hello</td>
</tr>
<tr>
<td>third</td>
<td>Apple</td>
<td>SDF hello</td>
</tr>
</tbody>
</table>
</body>
</html>
script.js
$(document).ready(function(){
$(".grid thead td").click(function(){
showFilterOption(this);
});
});
var arrayMap = {};
function showFilterOption(tdObject){
var filterGrid = $(tdObject).find(".filter");
if (filterGrid.is(":visible")){
filterGrid.hide();
return;
}
$(".filter").hide();
var index = 0;
filterGrid.empty();
var allSelected = true;
filterGrid.append('<div><input id="all" type="checkbox" checked>Select All</div>');
var $rows = $(tdObject).parents("table").find("tbody tr");
$rows.each(function(ind, ele){
var currentTd = $(ele).children()[$(tdObject).attr("index")];
var div = document.createElement("div");
div.classList.add("grid-item")
var str = $(ele).is(":visible") ? 'checked' : '';
if ($(ele).is(":hidden")){
allSelected = false;
}
div.innerHTML = '<input type="checkbox" '+str+' >'+currentTd.innerHTML;
filterGrid.append(div);
arrayMap[index] = ele;
index++;
});
if (!allSelected){
filterGrid.find("#all").removeAttr("checked");
}
filterGrid.append('<div><input id="close" type="button" value="Close"/><input id="ok" type="button" value="Ok"/></div>');
filterGrid.show();
var $closeBtn = filterGrid.find("#close");
var $okBtn = filterGrid.find("#ok");
var $checkElems = filterGrid.find("input[type='checkbox']");
var $gridItems = filterGrid.find(".grid-item");
var $all = filterGrid.find("#all");
$closeBtn.click(function(){
filterGrid.hide();
return false;
});
$okBtn.click(function(){
filterGrid.find(".grid-item").each(function(ind,ele){
if ($(ele).find("input").is(":checked")){
$(arrayMap[ind]).show();
}else{
$(arrayMap[ind]).hide();
}
});
filterGrid.hide();
return false;
});
$checkElems.click(function(event){
event.stopPropagation();
});
$gridItems.click(function(event){
var chk = $(this).find("input[type='checkbox']");
$(chk).prop("checked",!$(chk).is(":checked"));
});
$all.change(function(){
var chked = $(this).is(":checked");
filterGrid.find(".grid-item [type='checkbox']").prop("checked",chked);
})
filterGrid.click(function(event){
event.stopPropagation();
});
return filterGrid;
}
style.css
table thead tr td{
background-color : gray;
min-width : 100px;
position: relative;
}
.filter{
position:absolute;
border: solid 1px;
top : 20px;
background-color : white;
width:100px;
right:0;
display:none;
}
Maybe someone else will fix that limited JS for you but otherwise use DataTables. It has all you want with extensive documentation, and it's a popular plugin so it's not hard to find any answers to questions you might have about it. Here's an example with everything you desired in your post:
/* Range Search - https://datatables.net/examples/plug-ins/range_filtering.html */
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
var min = parseInt($('#min').val(), 10);
var max = parseInt($('#max').val(), 10);
var age = parseFloat(data[3]) || 0;
if (
(isNaN(min) && isNaN(max)) ||
(isNaN(min) && age <= max) ||
(min <= age && isNaN(max)) ||
(min <= age && age <= max)
) {
return true;
}
return false;
});
$(document).ready(function() {
/* Init dataTable - Options[paging: off, ordering: off, search input: off] */
var table = $('#table').DataTable({
"paging": false,
"ordering": false,
dom: 'lrt'
});
/* Column Filters */
$(".filterhead").each(function(i) {
if (i != 4 && i != 5) {
var select = $('<select><option value="">Filter</option></select>')
.appendTo($(this).empty())
.on('change', function() {
var term = $(this).val();
table.column(i).search(term, false, false).draw();
});
table.column(i).data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
} else {
$(this).empty();
}
});
/* Range Search -> Input Listener */
$('#min, #max').keyup(function() {
table.draw();
});
});
.container {
max-width: 80%;
margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.13.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.13.1/datatables.min.js"></script>
<body>
<div class="container">
<input type="text" id="min" name="min" placeholder="Min Number">
<input type="text" id="max" name="max" placeholder="Max number">
<table id="table" class="display">
<thead>
<tr>
<th class="filterhead">Name</th>
<th class="filterhead">Address</th>
<th class="filterhead">City</th>
<th class="filterhead">Number</th>
</tr>
<tr>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>first</td>
<td>first add</td>
<td>SDF dfd</td>
<td>18</td>
</tr>
<tr>
<td>second</td>
<td>as</td>
<td>SDF dfd</td>
<td>50</td>
</tr>
<tr>
<td>third</td>
<td>Apple</td>
<td>SDF dfd</td>
<td>2</td>
</tr>
<tr>
<td>third</td>
<td>as</td>
<td>SDF hello</td>
<td>25</td>
</tr>
<tr>
<td>third</td>
<td>Apple</td>
<td>SDF hello</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
</body>

how to output the minimum value from array on the website

i have the input values and js creates the array. I need that all values should be sorted by values and output the min value on the web page. User should see smth like this: the subject where u get (3(for example)) should be improved in next few days. please guys!
document.querySelector('button').addEventListener('click', function(e) {
var inputs = document.querySelectorAll('input');
var obj = [].reduce.call(inputs, (accumulator, currentValue, currentIndex) => {
accumulator[`val${currentIndex}`] = currentValue.value
return accumulator
}, {})
console.log(obj)
});
<form>
<table id="tblSearchTally">
<tr>
<td>Biology:<input type= "text" ></td>
</tr>
<tr>
<td>Chemistry:<input type= "text" ></td> </tr>
<tr>
<td>Physics:<input type= "text" ></td> </tr>
<tr>
<td>Math:<input type= "text" ></td>
</tr>
</table>
<button type="button">Go</button>
</form>
Details are commented in demo
// Reference the DOM elements
// Get the first <form> on page
const form = document.forms[0];
// Collect all form controls with [name=grade] into a NodeList
const inputs = form.elements.grade;
const minCell = document.querySelector('.MIN');
const maxCell = document.querySelector('.MAX');
// Register the <form> to the click event
form.onclick = calc;
// Event handler passes event object
function calc(e) {
// if clicked tag (ie e.target) is a button tag...
if (e.target.tagName === "BUTTON") {
/*
covert NodeList into an array
create an array of input values
and convert them into Numbers
then return the array of Numbers
in order from least to greatest
*/
let ordered = [...inputs].map(input => Number(input.value)).sort((a, b) => a - b);
console.log(ordered);
// Display the first Number of the Number array
minCell.textContent = ordered[0];
// Display the last Number of the Number array
maxCell.textContent = ordered[ordered.length - 1];
}
}
:root,
body {
font: 700 small-caps 2vw/1.45 Consolas;
}
table,
td {
table-layout: fixed;
border-collapse: collapse;
width: 200px;
border: 1px solid #000
}
td {
padding: 2px;
width: 50%;
text-align: right;
}
tfoot tr:first-of-type td {
text-align: left;
}
tfoot tr:first-of-type td::before {
content: attr(class)': ';
}
caption {
font-size: 1.25rem
}
input {
font: inherit;
text-align: right;
display: block;
width: 85px
}
button {
font: inherit;
text-align: right;
}
.as-console-wrapper {
width: 350px;
min-height: 100%;
margin-left: 45%;
}
<form>
<table>
<caption>Grades</caption>
<tbody>
<tr>
<td>Biology: </td>
<td><input name='grade' type="number" min='0' max='100' value='0'></td>
</tr>
<tr>
<td>Chemistry: </td>
<td><input name='grade' type="number" min='0' max='100' value='0'></td>
</tr>
<tr>
<td>Physics: </td>
<td><input name='grade' type="number" min='0' max='100' value='0'></td>
</tr>
<tr>
<td>Math: </td>
<td><input name='grade' type="number" min='0' max='100' value='0'></td>
</tr>
</tbody>
<tfoot>
<tr>
<td class='MIN'></td>
<td class='MAX'></td>
</tr>
<tr>
<td colspan='2'><button type="button">GO</button></td>
</tr>
</tfoot>
</table>
</form>
Put all the values in an array and use this: Math.min(...name_of_array) ;
Example:
var arr = [4,1,2,0,9,5];
Math.min(...arr) ;
The output will be: 0
create an array of scores, then calculate min value:
const scores = [...inputs].map( x => Number(x.value) );
const min = Math.min( ...scores );
Instead of reduce, you can use map to save inputs value into an array and sort it.
document.querySelector('button').addEventListener('click', function(e) {
var inputs = document.querySelectorAll('input');
var values = [].map.call(inputs, inputEl => inputEl.value);
values.sort();
console.log(values);
});
The minium value is values[0]
you can do like this by using jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<form>
<table id="tblSearchTally">
<tr>
<td>Biology:<input type="text" /></td>
</tr>
<tr>
<td>Chemistry:<input type="text" /></td>
</tr>
<tr>
<td>Physics:<input type="text" /></td>
</tr>
<tr>
<td>Math:<input type="text" /></td>
</tr>
</table>
<input type="button" onclick="MinValue('input')" value="Go" />
</form>
<script>
function MinValue(selector) {
var min = null;
$(selector).each(function () {
var value = parseInt(this.value, 0);
if (min === null || value < min) {
min = value;
}
});
console.log(min);
}
</script>

Auto calculation in table using jquery

My Requirment:
I have table with quantity cell as editable when change quantity it need to multiply with other parent td value.and sum the column values .
(i.e) if i change quantity to 2 then the parent rows need multiply by 2 & columns get value get added
I done all the calculation part the only thing when i delete or change the quantity the calculated value remain same how to revert back to old values
Here is my fiddle
Fiddle link
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
<!-- console.log(preVal); -->
if(preVal && preVal == val){
return;
}
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1){
return;
}
$(this).siblings().each(function(){
var tbvalue=$(this).text();
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
})
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i < 8; i++) {
var sum = 0;
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').each(function() {
sum += parseInt($(this).text()) || 0;
});
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>5</td>
<td>4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>8</td>
<td type>2</td>
<td>3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>20</td>
<td>3</td>
<td>5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
Inside every row, with the td that store the numbers to be multiplied, keep the original numbers in a data-val attribute in the td, and multiply your content editable value with that. Display the multiplied value as the td text. One change here is that, when you delete the value of contenteditable cell, it takes it as 1 for row calculation, but does not consider it for column multiplication.
HTML part
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td data-val="10">10</td>
<td data-val="5">5</td>
<td data-val="4">4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="8">8</td>
<td data-val="2">2</td>
<td data-val="3">3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="20">20</td>
<td data-val="3">3</td>
<td data-val="5">5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
JS Part
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1 || val == undefined){
val = 1;
}
$(this).siblings().each(function(){
var tbvalue=$(this).data("val");
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
});
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i <= 4; i++) {
var sum = 0;
var tdBoxes = $('.auto_sum>tbody>tr>td:nth-child(' + i + ')');
for(var j=0; j<tdBoxes.length-1;j++)
{
var value = $(tdBoxes[j]).text();
//alert(value);
sum += (value == undefined || value == "")? 0 : parseInt(value);
}
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
All details are commented in working demo. I added <form>, <output>, <input type='number'> and <input type='hidden'>. Also I don't remember <td> having a type attribute or a value of number either.
With the combination of the right elements and attributes (and maybe even a little CSS), you don't have to write so much JS/jQ because there many aspects of form functions built within HTML.
Demo
// Reference the <form>
var main = document.forms.main;
// Reference of all of <input> and <output> of <form>
var field = main.elements;
/* Register the input event on the <form>
|| ANY input event triggered within <form> will...
*/
main.addEventListener('input', function(e) {
// Check to see which field is the user inputing into
if (e.target !== e.currentTarget) {
// Reference that field
var input = document.getElementById(e.target.id);
// console.log(input.value);
// Get the row of the field
var row = input.parentNode.parentNode;
// console.log(row);
/* Gather all hidden fields of that row into a NodeList
|| and convert that NodeList into an array.
*/
var rowArray = Array.from(row.querySelectorAll('[type=hidden]'));
// console.log(rowArray);
// On each hidden field, perform the following function...
rowArray.forEach(function(cel, idx) {
// Get the value of hidden field
const base = cel.value;
// Find the <output> that comes after the hidden field
var output = cel.nextElementSibling;
/* Calculate the product of the hidden field's value
|| and the input field's value
*/
var val = parseInt(base, 10) * parseInt(input.value, 10);
// Display the prouct in the <output>
output.value = val;
});
/* Because we registered the input event on the <form>,
|| we have many ways to manipulate the <form>'s fields.
|| In this demo we have been using:
|| HTMLFormElement and HTMLFormControlsCollection interfaces
|| https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
|| http://www.dyn-web.com/tutorials/forms/references.php#dom0
*/
field.out1.value = Number(field.o1a.value) + Number(field.o1b.value) + Number(field.o1c.value);
field.out2.value = Number(field.o2a.value) + Number(field.o2b.value) + Number(field.o2c.value);
field.out3.value = Number(field.o3a.value) + Number(field.o3b.value) + Number(field.o3c.value);
field.out4.value = Number(field.out1.value) + Number(field.out2.value) + Number(field.out3.value);
}
});
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
input,
output {
display: inline-block;
font: inherit;
width: 6ch;
border: 0;
text-align: center;
}
.quantity input {
padding-top: .5em;
outline: 0;
}
-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<div class="container">
<form id='main'>
<table class="auto_sum table table-hover">
<thead>
<caption>
<h2>Table Calculation</h2>
<h3>Quanities</h3>
</caption>
<tr>
<th>Value1</th>
<th>Value2</th>
<th>Value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr id='rowA'>
<td>
<!--[0][1]-->
<input id='v1a' type='hidden' value='10'>
<output id='o1a'>0</output>
</td>
<td>
<!--[2][3]-->
<input id='v2a' type='hidden' value='5'>
<output id='o2a'>0</output>
</td>
<td>
<!--[4][5]-->
<input id='v3a' type='hidden' value='4'>
<output id='o3a'>0</output>
</td>
<td class="quantity">
<!--[6]-->
<input id='qa' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowB'>
<td>
<!--[7][8]-->
<input id='v1b' type='hidden' value='8'>
<output id='o1b'>0</output>
</td>
<td>
<!--[9][10]-->
<input id='v2b' type='hidden' value='2'>
<output id='o2b'>0</output>
</td>
<td>
<!--[11][12]-->
<input id='v3b' type='hidden' value='3'>
<output id='o3b'>0</output>
</td>
<td class="quantity">
<!--[13]-->
<input id='qb' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowC'>
<td>
<!--[14][15]-->
<input id='v1c' type='hidden' value='20'>
<output id='o1c'>0</output>
</td>
<td>
<!--[16][17]-->
<input id='v2c' type='hidden' value='3'>
<output id='o2c'>0</output>
</td>
<td>
<!--[18][19]-->
<input id='v3c' type='hidden' value='5'>
<output id='o3c'>0</output>
</td>
<td class="quantity">
<!--[20]-->
<input id='qc' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr class="total">
<td>
<!--[21]-->
<output id='out1' for='o1a o1b o1c'>0</output>
</td>
<td>
<!--[22]-->
<output id='out2' for='o2a o2b o2c'>0</output>
</td>
<td>
<!--[23]-->
<output id='out3' for='o3a o3b o3c'>0</output>
</td>
<td>
<!--[24]-->
<output id='out4' for='out1 out2 out3'>0</output>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

add dynamic input field with unique id for counting

I am working on a code to calculate the total price of services.
Now if I add the hours (like 2) and add the price per hour (like 20) the code has to calculate the price that will become the subtotal. After that It calculate the "BTW" (tax) and add it to the subtotal for the total price.
What I would like is to add dynamic new input fields with a unique id so the code can calculate multiple services. So for each service you've got a total amount which all combined will be the subtotal. My code for now:
HTML
<table class="table-responsive table" id="table-diensten">
<thead>
<tr>
<th>Time</th>
<th>Service</th>
<th>amount</th>
<th>total</th>
<th>BTW</th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td><input type="text" class="form-control" placeholder="time (in hours)" id="time" onchange="totalofferte()"></td>
<td><input type="text" class="form-control" placeholder="service"></td>
<td><input type="text" class="form-control" placeholder="Cost (per hour)" id="cost" onchange="totalofferte()"></td>
<td>€ <span id="total">0,00</span></td>
<td>21%</td>
</tr>
</tbody>
<tfoot>
<tr>
<td> </td>
<td> </td>
<td><strong>Subtotaal</strong></td>
<td>€ <span id="subtotal">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>21% BTW</td>
<td>€ <span id="costbtw">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="table-total"><span class="total">Totaal</span></td>
<td class="table-total"><span class="total">€ <span id="totalofferte">0,00</span></span></td>
<td> </td>
</tr>
</tfoot>
</table>
<a href="#table-diensten" class="add-tablerow btn btn-default" >add new service</a>
JS
<script type="text/javascript">
function totalofferte() {
var cost = document.getElementById('cost').value;
var time = document.getElementById('time').value;
if (cost > 0 && time > 0) {
var total = cost * time;
if (total > 0) {
document.getElementById('total').innerHTML = total;
var subtotal = total;
if (subtotal > 0) {
document.getElementById('subtotal').innerHTML = subtotal;
var costbtw = subtotal / 100 * 21;
document.getElementById('costbtw').innerHTML = costbtw;
var totalofferte = subtotal + costbtw;
document.getElementById('totalofferte').innerHTML = totalofferte;
}
}
}
}
</script>
Edit:
Forgot my JQuery
$(".add-tablerow").click(function(){
$( ".table-body" ).append("<tr class='table-row'><td><input type='text' class='form-control' placeholder='Tijd'></td><td><input type='text' class='form-control' placeholder='Omschrijving'></td><td><input type='text' class='form-control' placeholder='Kosten'></td><td>€ 0,00</td><td>21%</td></tr>");
});
Using addNewRow method you can achieve the behaviour you are expecting
function addNewRow(){
var presentRows = $("#table-diensten > tbody > tr");
var newRowId = presentRows.length + 1;
$("#table-diensten").append(
'<tr id="' + newRowId + '">' +
'<td><input class="form-control" type="number" name="time_' + newRowId + '" id="time_' + newRowId + '"/></td>' +
'<td><input class="form-control" type="number" name="service_' + newRowId + '" id="service_' + newRowId + '"/></td>' +
'<td><input class="form-control" type="number" name="amount' + newRowId + '" id="amount' + newRowId + '"/></td>' +
'<td></td>' +
'<td></td>' +
'</tr>'
);
}
function totalofferte() {
var cost = document.getElementById('cost').value;
var time = document.getElementById('time').value;
if (cost > 0 && time > 0) {
var total = cost * time;
if (total > 0) {
document.getElementById('total').innerHTML = total;
var subtotal = total;
if (subtotal > 0) {
document.getElementById('subtotal').innerHTML = subtotal;
var costbtw = subtotal / 100 * 21;
document.getElementById('costbtw').innerHTML = costbtw;
var totalofferte = subtotal + costbtw;
document.getElementById('totalofferte').innerHTML = totalofferte;
}
}
}
}
.navigation {
width: 300px;
}
.mainmenu, .submenu {
list-style: none;
padding: 0;
margin: 0;
}
.mainmenu a {
display: block;
background-color: #CCC;
text-decoration: none;
padding: 10px;
color: #000;
}
.mainmenu li:hover a,
.mainmenu li.active a {
background-color: #C5C5C5;
}
.mainmenu li.active .submenu {
display: block;
max-height: 200px;
}
.submenu a {
background-color: #999;
}
.submenu a:hover {
background-color: #666;
}
.submenu {
overflow: hidden;
max-height: 0;
-webkit-transition: all 0.5s ease-out;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-responsive table" id="table-diensten">
<thead>
<tr>
<th>Time</th>
<th>Service</th>
<th>amount</th>
<th>total</th>
<th>BTW</th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td><input type="text" class="form-control" placeholder="time (in hours)" id="time" onchange="totalofferte()"></td>
<td><input type="text" class="form-control" placeholder="service"></td>
<td><input type="text" class="form-control" placeholder="Cost (per hour)" id="cost" onchange="totalofferte()"></td>
<td>€ <span id="total">0,00</span></td>
<td>21%</td>
</tr>
</tbody>
<tfoot>
<tr>
<td> </td>
<td> </td>
<td><strong>Subtotaal</strong></td>
<td>€ <span id="subtotal">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>21% BTW</td>
<td>€ <span id="costbtw">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="table-total"><span class="total">Totaal</span></td>
<td class="table-total"><span class="total">€ <span id="totalofferte">0,00</span></span></td>
<td> </td>
</tr>
</tfoot>
</table>
add new service
its very simple. Frist create your element example:
var input = $("<input/>").attr({
name: 'EmailSend',
type: 'text',
value: true,
class: "YOURClass"
id: "YouRid"
});
Than append your crated input to your wish element. example: $( ".table-body" ).append(input)
Adding items in DOM through Javascript
In order to add new Items in your table with Native Javascript you will have to use one of the following
Element.insertAdjacentHTML()
Element.innerHTML
Node.appendChild()
If you want to use jQuery instead then you can try
.append()
.html()
Add custom attributes to DOM items
If you want to add a new attribute on a DOM element , you can do it with Native Javascript using the
element.setAttribute(name, value);
or with jQuery
.attr();
Loop through items
Now in order to "process" those new values each time , you need to iterate through all your inputs and carry your calculations. Iteration can be done in Native Javascript through the use of
Element.getElementsByTagName() If all inputs should be processed in your Table.
Document.getElementsByClassName() If you assign a specific class on each of your inputs and only those will be processed.
or if you want to use jQuery you could go on with
jQuery.each()

Javascript Functions for Form are not Displaying with textContent

In my current code, I have a form that takes in 4 input quantities. Once inputted, the user will click the purchase button and the total counts of: total items, subtotal, sales tax, total and final discount amount will display based on what the user previously inputted.
My current issue is that nothing seems to print. Not even my error checking print.
So far all that displays is the current "0" values for each value for the shopping cart.
Please help me understand where my issues lie.
I have some concern that the getElementsByClassId may be causing my problem too for the class inside the () for it. Not completely sure where to start.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Set the viewport so this responsive site displays correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page title </title>
<!-- Include bootstrap CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Include jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
thead { background-color: #333; color: #fff; font-weight: bold; }
.items, #nitems, #subtotal, #tax, #total, #final {text-align: right; width: 100px; }
#checkout { margin-bottom: 45px; width: 200px; height: 50px; font-weight: bold; }
#errors { padding-bottom: 200px; clear: both; font-weight: bold; clear: both; font-size: 20px;
color: blue;
}
</style>
</head>
<body class='container'>
<form name="testForm">
<div class='row'>
<div class='col-md-8'>
<h2>Sam's Online Shop</h2>
<h3>15% discount on all online sales </h3>
<h3>Our World Famous Chocolates Now Available Online </h3>
<table class='table'>
<thead>
<tr>
<th>Product</th><th>Unit cost</th><th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td id="ch-1-label">Milk Chocolate</td>
<td id="ch-1-cost">7.48</td>
<td><input size=3 name="milkchoc" id="ch-1-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-2-label">Assorted Fine Chocolates</td>
<td id="ch-2-cost">9.98</td>
<td><input size=3 name="foil" id="ch-2-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-3-label">Assorted Milk & Dark Chocolates</td>
<td id="ch-3-cost">12.98</td>
<td><input size=3 name="dc" id="ch-3-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-4-label">Assorted Dessert Truffles</td>
<td id="ch-4-cost">15.98</td>
<td><input size=3 name="dt" id="ch-4-qnt" class="form-control items" value="0"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-md-4'>
<h3>Shopping Cart </h3>
<table class='table'>
<tr>
<td>Total Items</td>
<td><span id="nitems" >0</td>
</tr>
<tr>
<td>Subtotal</td>
<td><span id="subtotal" >0</td>
</tr>
<tr>
<td>5% Sales tax</td>
<td><span id="tax" >0</td>
</tr>
<tr>
<td>Total</td>
<td><span id="total" >0</td>
</tr>
<tr>
<td>Final amount (with 15% discount)</td>
<td><span id="final" >0</td>
</tr>
</table>
<p><input type="button" value="Purchase" id="checkout" class="form-control btn btn-primary" /></p>
<p><span id='errors'></span></p>
</div>
</div>
JAVASCRIPT CODE AT BOTTOM OF HTML CODE
<script>
// Include Javascript code here
document.getElementById('Purchase').onclick = function() {
var milk = document.getElementById('ch-1-qnt').value;
var fine = document.getElementById('ch-2-qnt').value;
var both = document.getElementById('ch-3-qnt').value;
var truff = document.getElementById('ch-4-qnt').value;
//Check for errors
var errors = checkErrors();
//Display the errors
if (errors.length > 0)
//displayErrors(errors);
checkErrors();
}
else {
// Display function for total count of items purchased
displayitems();
// Return subTotal function that totals the initial cost for all
var subTotal = Sub(milk, fine, both, truff);
document.getElementByID('subtotal').textContent = subTotal;
//Return Tax function totals
var salesTax = Tax(subTotal);
document.getElementById('tax').textContent = salesTax;
// Return the total cost for Subtotal cost and salesTax cost
var Total = displayTotal(subTotal, salesTax);
document.getElementById('total').textContent = Total;
// Display discount pricing
var DiscountTotal = Total * .15;
document.getElementById('final').textContent = DiscountTotal;
}
//Returns an array of error messages
function checkErrors() {
var list = [];
for (var j = 1; j<4; j++){
if (document.getElementById('ch-' + j + '-qnt')).value <0 ) {
document.getElementById('errors').innerHTML = list;
}
}
}
// Display total item counts
function displayItems() {
var total = 0;
var input = document.getElementsByClassId('form-control items');
for (var i=0; i<input.length; i++){
total += parseFloat(input[i].value);
}
document.getElementById('nitems').textContent = total;
}
//Function to return the subtotal for all 4 inputs
function Sub(milk, fine, both, truff) {
var total1, total2, total3, total4 = 0;
var Final = 0;
var costMilk = 7.48;
var costFine = 9.98;
var costBoth = 12.98;
var costTruff = 15.98;
total1 = costMilk * milk;
total2 = costFine *fine;
total3 = costBoth * both;
total4 = costTruff * truff;
Final = total1 + total2 + total3 + total4;
return Final;
}
// Returns tax total
function Tax(subTotal) {
subTotal = Sub(milk, fine, both, truff);
var Tax = subTotal * .05;
return Tax;
}
function displayTotal(Tax, Sub){
return Tax * Sub;
}
};
</script>
</body>
</html>
You have many errors on your scripts, the list of errors are
document.getElementById('Purchase').onclick // using wrong id Purchase but checkout
if (errors.length > 0) //forgot closing brace {, but if (errors.length > 0){
displayitems(); //wrong function calling, but displayItems()
document.getElementsByClassId('form-control items'); //should be document.getElementsByClassName
(document.getElementById('ch-' + j + '-qnt').value) <0 ) //extra parenthesis ) after value, but (document.getElementById('ch-' + j + '-qnt').value <0 )
document.getElementById('checkout').onclick = function() {
var milk = document.getElementById('ch-1-qnt').value;
var fine = document.getElementById('ch-2-qnt').value;
var both = document.getElementById('ch-3-qnt').value;
var truff = document.getElementById('ch-4-qnt').value;
//Check for errors
var errors = checkErrors();
//Display the errors
if (errors.length > 0) {
//displayErrors(errors);
checkErrors();
}else {
// Display function for total count of items purchased
displayItems();
// Return subTotal function that totals the initial cost for all
var subTotal = Sub(milk, fine, both, truff);
document.getElementById('subtotal').textContent = subTotal;
//Return Tax function totals
var salesTax = Tax(subTotal);
document.getElementById('tax').textContent = salesTax;
// Return the total cost for Subtotal cost and salesTax cost
var Total = displayTotal(subTotal, salesTax);
document.getElementById('total').textContent = Total;
// Display discount pricing
var DiscountTotal = Total * .15;
document.getElementById('final').textContent = DiscountTotal;
}
//Returns an array of error messages
function checkErrors() {
var list = [];
for (var j = 1; j<4; j++){
if (document.getElementById('ch-' + j + '-qnt').value <0 ) {
document.getElementById('errors').innerHTML = list;
}
}
return list;
}
// Display total item counts
function displayItems() {
var total = 0;
var input = document.getElementsByClassName('form-control items');
for (var i=0; i<input.length; i++){
total += parseFloat(input[i].value);
}
document.getElementById('nitems').textContent = total;
}
//Function to return the subtotal for all 4 inputs
function Sub(milk, fine, both, truff) {
var total1, total2, total3, total4 = 0;
var Final = 0;
var costMilk = 7.48;
var costFine = 9.98;
var costBoth = 12.98;
var costTruff = 15.98;
total1 = costMilk * milk;
total2 = costFine *fine;
total3 = costBoth * both;
total4 = costTruff * truff;
Final = total1 + total2 + total3 + total4;
return Final;
}
// Returns tax total
function Tax(subTotal) {
subTotal = Sub(milk, fine, both, truff);
var Tax = subTotal * .05;
return Tax;
}
function displayTotal(Tax, Sub){
return Tax * Sub;
}
};
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Include jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
thead { background-color: #333; color: #fff; font-weight: bold; }
.items, #nitems, #subtotal, #tax, #total, #final {text-align: right; width: 100px; }
#checkout { margin-bottom: 45px; width: 200px; height: 50px; font-weight: bold; }
#errors { padding-bottom: 200px; clear: both; font-weight: bold; clear: both; font-size: 20px;
color: blue;
}
</style>
</head>
<body class='container'>
<form name="testForm">
<div class='row'>
<div class='col-md-8'>
<h2>Sam's Online Shop</h2>
<h3>15% discount on all online sales </h3>
<h3>Our World Famous Chocolates Now Available Online </h3>
<table class='table'>
<thead>
<tr>
<th>Product</th><th>Unit cost</th><th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td id="ch-1-label">Milk Chocolate</td>
<td id="ch-1-cost">7.48</td>
<td><input size=3 name="milkchoc" id="ch-1-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-2-label">Assorted Fine Chocolates</td>
<td id="ch-2-cost">9.98</td>
<td><input size=3 name="foil" id="ch-2-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-3-label">Assorted Milk & Dark Chocolates</td>
<td id="ch-3-cost">12.98</td>
<td><input size=3 name="dc" id="ch-3-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-4-label">Assorted Dessert Truffles</td>
<td id="ch-4-cost">15.98</td>
<td><input size=3 name="dt" id="ch-4-qnt" class="form-control items" value="0"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-md-4'>
<h3>Shopping Cart </h3>
<table class='table'>
<tr>
<td>Total Items</td>
<td><span id="nitems" >0</td>
</tr>
<tr>
<td>Subtotal</td>
<td><span id="subtotal" >0</td>
</tr>
<tr>
<td>5% Sales tax</td>
<td><span id="tax" >0</td>
</tr>
<tr>
<td>Total</td>
<td><span id="total" >0</td>
</tr>
<tr>
<td>Final amount (with 15% discount)</td>
<td><span id="final" >0</td>
</tr>
</table>
<p><input type="button" value="Purchase" id="checkout" class="form-control btn btn-primary" /></p>
<p><span id='errors'></span></p>
</div>
</div>

Categories

Resources