Multiple calculations in html / javascript code - text box data entry - javascript

I have asked this question before but have had to clean it up, difficult to follow, cause it was a mess, so its down to the bone now, in the format below the code works, the issue I am having is that I want to add a second and third equation using the same variables, possibly a forth, I thought I could just add another equation in the same format below and would work (different ID), but its not, it calculates one and not the other, its for a stand alone computer, no internet, can't use any plugins either, been at it a while now and its annoying me but I am determined to get it to work. Its google chrome being used. Is this possible, any one help please. I have set the code back to calculating just the one equation.
<!DOCTYPE html>
<html>
<head> </head>
<body>
<script type="text/javascript">
window.onload = function() {
CMCObj = document.getElementById('txtCMC');
WaterObj = document.getElementById('txtWater');
GlycerolObj = document.getElementById('txtGlycerol');
FlowObj = document.getElementById('txtFlow');
FreshObj = document.getElementById('tdFresh');
document.getElementById('btnReset').onclick = resetInputs;
document.getElementById('btnCalc').onclick = calcAddition;
};
function resetInputs() {
CMCObj.value = '';
WaterObj.value = '';
GlycerolObj.value = '';
FlowObj.value = '';
FreshObj.innerHTML = '';
}
function calcAddition() {
var CMC = new Number(CMCObj.value);
var Water = new Number(WaterObj.value);
var Glycerol = new Number(GlycerolObj.value);
var Flow = new Number(FlowObj.value);
FreshObj.innerHTML = '';
if (isNaN(CMC) || isNaN(Water)) {
alert('Invalid CMC or Water');
return;
}
FreshObj.innerHTML = Math.round(
((CMC + Water + Glycerol) / (CMC + Water + Glycerol + Flow)) * 100
);
}
</script>
<table>
<tr>
<td><label for="txtCMC">Total CMC Injection (ml)</label></td>
<td><input type="text" id="txtCMC" /></td>
</tr>
<tr>
<td><label for="txtWater">Total Water Injection (ml)</label></td>
<td><input type="text" id="txtWater" /></td>
</tr>
<tr>
<td><label for="txtGlycerol">Total Glycerol Injection (%)</label></td>
<td><input type="text" id="txtGlycerol" /></td>
</tr>
<tr>
<td><label for="txtFlow">Plasticiser Flow (Lhr)</label></td>
<td><input type="text" id="txtFlow" /></td>
</tr>
<tr>
<td>Total Fresh Injection (%)</td>
<td id="tdFresh"></td>
</tr>
<tr>
<td></td>
<td>
<button id="btnReset">Reset</button
><button id="btnCalc">Calculate</button>
</td>
</tr>
</table>
</body>
</html>
Fixed code below and it works, thanks for help
<!DOCTYPE html>
<html>
<head>
</head>
<BODY>
<script type="text/javascript">
window.onload=function() {
CMCObj = document.getElementById('txtCMC');
WaterObj = document.getElementById('txtWater');
GlycerolObj = document.getElementById('txtGlycerol');
FlowObj = document.getElementById('txtFlow');
FreshObj = document.getElementById('tdFresh');
FreshCMCObj = document.getElementById('tdFreshCMC');
FreshGlycerolObj = document.getElementById('tdFreshGlycerol');
document.getElementById('btnReset').onclick = resetInputs;
document.getElementById('btnCalc').onclick = calcAddition;
}
function resetInputs() {
CMCObj.value = '';
WaterObj.value = '';
GlycerolObj.value = '';
FlowObj.value = '';
FreshObj.innerHTML = '';
FreshCMCObj.innerHTML = '';
FreshGlycerolObj.innerHTML = '';
}
function calcAddition() {
var CMC = new Number(CMCObj.value);
var Water = new Number(WaterObj.value);
var Glycerol = new Number(GlycerolObj.value);
var Flow = new Number(FlowObj.value);
FreshObj.innerHTML = '';
if(isNaN(CMC) || isNaN(Water)) {
alert('Invalid CMC or Water');
return;
}
FreshCMCObj.innerHTML = '';
if(isNaN(CMC) || isNaN(Water)) {
alert('Invalid CMC or Water');
return;
}
FreshGlycerolObj.innerHTML = '';
if(isNaN(CMC) || isNaN(Water)) {
alert('Invalid CMC or Water');
return;
}
FreshObj.innerHTML = Math.round(((CMC+Water+Glycerol)/(CMC+Water+Glycerol+Flow)*100));
FreshCMCObj.innerHTML = Math.round(((CMC)/(CMC+Water+Glycerol+Flow)*100));
FreshGlycerolObj.innerHTML = Math.round(((CMC+Water+Glycerol)/(CMC+Water+Glycerol+Flow)*100));
}
</script>
<table>
<tr>
<td><label for="txtCMC">Total CMC Injection (ml)</label></td>
<td><input type="text" id="txtCMC" /></td>
</tr>
<tr>
<td><label for="txtWater">Total Water Injection (ml)</label></td>
<td><input type="text" id="txtWater" /></td>
</tr>
<tr>
<td><label for="txtGlycerol">Total Glycerol Injection (%)</label></td>
<td><input type="text" id="txtGlycerol" /></td>
</tr>
<tr>
<td><label for="txtFlow">Plasticiser Flow (Lhr)</label></td>
<td><input type="text" id="txtFlow" /></td>
</tr>
<tr>
<td>Total Fresh Injection (%)</td>
<td id="tdFresh"></td>
</tr>
<tr>
<td>Total Fresh CMC Injection (%)</td>
<td id="tdFreshCMC"></td>
</tr>
<tr>
<td>Total Fresh Glycerol Injection (%)</td>
<td id="tdFreshGlycerol"></td>
</tr>
<tr>
<td></td>
<td><button id="btnReset">Reset</button><button id="btnCalc">Calculate</button></td>
</tr>
</table>
</body>
</html>

Alright, I made a few changes to your code making your calculator fully dynamic. If you change the FormMaker function's TotalForms variable to any number... thats how many calculators it will make for you. enjoy
:)
Also, I almost forgot to mention. Your JS script needs to be placed at the end of your HTML document and never on top. There are ways to place your JS at the top, but it should be done with built workarounds to avoid errors in your code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>My Calculator</title>
</head>
<body>
<div id="FormArea"></div>
<script type="text/javascript">
//setTimeout(FormMaker, 0);
(function StartingApp(){
setTimeout(FormMaker, 6);
})();
function FormMaker() {
let TotalForms = 3,
i,
fragment,
div,
htmlText,
Location = document.querySelector('#FormArea');
console.log(Location);
for (i = 0; i < TotalForms; i++) {
console.log('hello');
fragment = document.createDocumentFragment();
div = document.createElement('div');
htmlText = `
<h2>Amazing Calculator ${i+1}</h2>
<table>
<tr>
<td><label for="txtCMC">Total CMC Injection (ml)</label></td>
<td><input type="text" id="txtCMC${i}" /></td>
</tr>
<tr>
<td><label for="txtWater">Total Water Injection (ml)</label></td>
<td><input type="text" id="txtWater${i}" /></td>
</tr>
<tr>
<td><label for="txtGlycerol">Total Glycerol Injection (%)</label></td>
<td><input type="text" id="txtGlycerol${i}" /></td>
</tr>
<tr>
<td><label for="txtFlow">Plasticiser Flow (Lhr)</label></td>
<td><input type="text" id="txtFlow${i}" /></td>
</tr>
<tr>
<td>Total Fresh Injection (%)</td>
<td id="tdFresh${i}"></td>
</tr>
<tr>
<td></td>
<td>
<button id="btnReset${i}" onclick = "resetInputs()">Reset</button>
<button id="btnCalc${i}" onclick = "calcAddition()">Calculate</button>
</td>
</tr>
</table>
`;
div.className = 'FormContainers';
div.innerHTML = htmlText;
fragment.appendChild(div);
Location.appendChild(fragment);
};
};
function resetInputs() {
let i,
TotalForms = document.getElementsByClassName("FormContainers").length;
for (i = 0; i < TotalForms; i++) {
let CMCObj = document.getElementById(`txtCMC${i}`),
WaterObj = document.getElementById(`txtWater${i}`),
GlycerolObj = document.getElementById(`txtGlycerol${i}`),
FlowObj = document.getElementById(`txtFlow${i}`),
FreshObj = document.getElementById(`tdFresh${i}`);
CMCObj.value = '';
WaterObj.value = '';
GlycerolObj.value = '';
FlowObj.value = '';
FreshObj.innerHTML = '';
};
};
function calcAddition() {
let i,
TotalForms = document.getElementsByClassName("FormContainers").length;
for (i = 0; i < TotalForms; i++) {
let CMC = document.getElementById(`txtCMC${i}`).value,
Water = document.getElementById(`txtWater${i}`).value,
Glycerol = document.getElementById(`txtGlycerol${i}`).value,
Flow = document.getElementById(`txtFlow${i}`).value,
FreshObj = document.getElementById(`tdFresh${i}`);
FreshObj.innerHTML = '';
if(isNaN(CMC) || isNaN(Water)) {
alert(`Invalid CMC or Water on Amazing Calculator ${i}`);
return;
}
FreshObj.innerHTML = Math.round(((CMC+Water+Glycerol)/(CMC+Water+Glycerol+Flow)*100));
};
};
</script>
<style>
#FormArea{
display: flex;
flex-wrap: wrap;
}
</style>
</body>
</html>

Related

In the first page i was passing the values in textbox then i should get the data in second page in text box using only Javascript?

In the first page entered the values using text box,In second page also it should display in the text box.But it is not displaying like that.......
Below is my first page pass.html:
<html>
<head>
<script type="text/javascript">function getParams()
{
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx !=-1)
{
var pairs = document.URL.substring(idx+1,
document.URL.length).split('&');
for (var i=0; i<pairs.length; i++)
{
console.log(pairs.length);
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</head>
</html>
And below is my second page pass1.html
<html>
<form type=get action="pass1.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=number name=age></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</html>

Is there a better way to setup the input checked attribute?

My first thought was to set the input checked = "javascript function() true/false" is this possible?
What I am trying to do is a select all checkbox for my forum mailbox system.
I am useing a table to display the inbox and placed the select all checkbox inside.
<form action="" method = "post">
<table rules="all">
<tr>
<th>
<input type="checkbox" id = "setchecked" name="smessgage"value="deleteall" onclick="get_checked()"/>
</th>
<th>From</th>
<th>Subject</th>
<th>Date</th>
</tr>
I use
onclick="get_checked()
to call this javascript function which sets the other checkboxes checked attribute.
<script>
function get_checked()
{
if(document.getElementById("setchecked").checked)
{
for(var i = 0; i < 100;++i)
{
var check_id = "smessage"+i;
if(document.getElementById(check_id))
document.getElementById(check_id).checked = true;
}
}
else
{
for(var i = 0; i < 100;++i)
{
var check_id = "smessage"+i;
if(document.getElementById(check_id))
document.getElementById(check_id).checked = false;
}
}
}
</script>
The php to set the table up looks like this.
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if(isset($row['to_']) && $row['to_'] == $_SESSION['user_name'])
{
$id_ = isset($row['id']) ? $row['id'] : '';
$top_ = isset($row['subject']) ? $row['subject'] : '';
$auth_ = isset($row['from_']) ? $row['from_'] : '';
$date_ = isset($row['date']) ? $row['date'] : '';
echo '<tr id = "cat_" name = "cat_1">
<td style = "margin:0 auto; text-align:center;"><input type="checkbox" id = "smessage'.$i.'" name="smessgage" value="'.$id_.'"/></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
$auth_.'</a></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
$top_.'</a></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
time_elapsed_string($date_,true).'</a></td></tr>';
++$i;
}
}
This works as expected but seems a bit overkill. I just want to know if there is a more relastic approach or something that I missed while looking over input types?
Here is your improved version. Basically you just need to use same class for all checkbox before each line of your message, so that you can use jQuery.each() function to select all and toggle the checked property based on your main checkbox, which has id "setchecked"
Hope this help,
KD Quality
function checkAll(bx) {
var cbs = jQuery(".checkbox_class").each(function() {
jQuery(this).prop('checked', jQuery('#setchecked').prop('checked'));
});
}
var e = document.getElementById('setchecked'); e.onclick = checkAll;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="post">
<table rules="all">
<tr>
<th>
<input type="checkbox" id="setchecked" name="smessgage" value="deleteall" />
</th>
<th>From</th>
<th>Subject</th>
<th>Date</th>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_1" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_2" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_3" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
</table>
</form>
You could do something like this
// The important code
function selectAll(e) {
var nodes = document.querySelectorAll('form input[type=checkbox]');
for(var i = 0; i < nodes.length; i++) {
nodes[i].checked = e.target.checked;
};
}
// This is only code to genereate input elements
var form = document.getElementById('foo');
for (var i = 0; i < 15; i++) {
var input = document.createElement('input');
input.type = "checkbox";
form.appendChild(input);
}
<input id="selectall" type="checkbox" onclick="selectAll(event)" />
<label for="selectall">Select all</label>
<hr />
<form id="foo"></form>

losing changes after modifying html (DOM)

I am using netbeans with chrome extension (netbeans connector) , i created a jsp page like this :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Page</title>
</head>
<body>
<div align = "center">
<form >
<table border="0">
<tbody>
<tr>
<td>Name : </td>
<td><input type="text" name="Name" value="" /></td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="Password" value="" /></td>
</tr>
<tr>
<td>Age : </td>
<td><input type="text" name="Age" value="" /></td>
</tr>
<tr>
<td></td>
<td><input type="reset" value="Reset" style="float: right"/>
<input type="submit" value="Submit" style="float: right" onclick="onSubmit()" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div align = "center">
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script language = "javascript">
function onSubmit(){
var name = document.getElementsByName('Name')[0] ;
var password = document.getElementsByName('Password')[0] ;
var age = document.getElementsByName('Age')[0] ;
if(age.value >= 50){
alert('You\'re too old !');
}
var table = document.getElementsByTagName('table')[1] ;
var body = table.getElementsByTagName('tbody')[0] ;
var trNode = document.createElement('tr') ;
var thNameNode = document.createElement('td') ;
var nameTextNode = document.createTextNode(name.value.toString()) ;
thNameNode.appendChild(nameTextNode) ;
var thAgeNode = document.createElement('td') ;
var ageTextNode = document.createTextNode(age.value) ;
thAgeNode.appendChild(ageTextNode) ;
trNode.appendChild(thNameNode) ;
trNode.appendChild(thAgeNode) ;
body.appendChild(trNode) ;
}
</script>
</body>
the function onSubmit() is supposed to add a row in the table dynamically, but when i run on the browser the changes appear briefly and i am redirected again to original page , what is exactly the problem?
Form gets submitted on onSubmit function, you can prevent it by return false.
So below should work
function onSubmit(){
var name = document.getElementsByName('Name')[0] ;
var password = document.getElementsByName('Password')[0] ;
var age = document.getElementsByName('Age')[0] ;
if(age.value >= 50){
alert('You\'re too old !');
}
var table = document.getElementsByTagName('table')[1] ;
var body = table.getElementsByTagName('tbody')[0] ;
var trNode = document.createElement('tr') ;
var thNameNode = document.createElement('td') ;
var nameTextNode = document.createTextNode(name.value.toString()) ;
thNameNode.appendChild(nameTextNode) ;
var thAgeNode = document.createElement('td') ;
var ageTextNode = document.createTextNode(age.value) ;
thAgeNode.appendChild(ageTextNode) ;
trNode.appendChild(thNameNode) ;
trNode.appendChild(thAgeNode) ;
body.appendChild(trNode) ;
return false;
}
You have few options to achieve this.
Use type = 'button' instead of type= 'submit'
Use return false in click handler. Not to forget return in inline event binding. e.g. onclick='return onSubmit()'. Fiddle here
Use e.preventDefault() Fiddle here

How to get sum of onload inputs

HTML:
<table id="tab1">
<tr id="maint">
<td style="background-color:white;"></td>
<td>słowo klucz</td>
<td>ilość wynikow google</td>
</tr>
<tr>
<td id="maint">słowo klucz</td>
<td><input type="text" name="klucz" value="" required></td>
<td><input type="number" name="wyszkiwania" value="" onblur="sumX()" onkeyup="operatorf()" id="eq"required></td>
</tr>
<tr>
<td id="maint">słowo klucz</td>
<td><input type="text" name="klucz" value=""></td>
<td><input type="number" name="wyszkiwania" value="" onblur="sumX()" onkeyup="operatorf()" id="eq"required></td>
</tr>
</table>
JS:
var wejscie = document.getElementById('eq').value;
if ( wejscie <= 100000) {
var stawka13 = 59;
var stawka46 = stawka13*0.75;
var stawka710 = stawka46*0.55;
}
else {
var stawka13 = wejscie/100000*59;
if (stawka13 > 210) {
stawka13 = 210;
}
var stawka46 = stawka13*0.75;
var stawka710 = stawka46*0.55;
}
stawka13 = Math.round(stawka13).toFixed(2);
stawka46 = Math.round(stawka46).toFixed(2);
stawka710 = Math.round(stawka710).toFixed(2);
document.getElementById('sum13').innerHTML = "";
document.getElementById('sum46').innerHTML = "";
document.getElementById('sum710').innerHTML = "";
document.getElementById('sum13').innerHTML = " "+sum13+" zł";
document.getElementById('sum46').innerHTML = " "+sum46+" zł";
document.getElementById('sum710').innerHTML = " "+sum710+" zł";
I would like to get an sum of it but with this eq.
I try arr etc but aint work "properly" as I want.
My target is just sum all of it with all math in it.
I'm not allowed to add jq to it so it is impotant to stay on meta.

jquery sum of dynamically added textboxes

i have a page where i can add and delete rows with a textbox with class 'prijs'. when the page is loaded there is already one row.
now i need to sum the values of all textboxes with class 'prijs' and display it in a TD with id 'totaalexbtw'. here is my problem: it doesn't loop through the added textboxes. also, when a textbox is deleted the total should be affected.
Some help would be very appreciated!! I am stuck for days!
Thanks in advance!
<html>
<head>
<script type="text/javascript" src="javascript/jquery_v2.0.3.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function kiesklant(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("klantinfo").innerHTML="<table><tr><td>Naam:</td><td</td></tr><td>Adres:</td><td></td></tr><td>Tel:</td><td></td></tr>";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("klantinfo").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "kiesklant.php?q="+str, true);
xmlhttp.send();
};
var linenumber = 0;
function addLine()
{
linenumber++;
var newRow = document.createElement('tr');
var newCell = document.createElement('td');
newCell = document.createElement('td');
var inputNode = document.createElement('input');
inputNode.name = 'dienstomschrijving';
inputNode.setAttribute('type', 'text');
inputNode.setAttribute('style', 'width: 200px');
newCell.appendChild(inputNode);
newRow.appendChild(newCell);
newCell = document.createElement('td');
inputNode = document.createElement('input');
inputNode.name = 'prijs';
inputNode.setAttribute('type', 'text');
inputNode.setAttribute('style', 'width: 100px');
inputNode.className = 'prijs';
newCell.appendChild(inputNode);
newRow.appendChild(newCell);
newCell = document.createElement('td');
inputNode = document.createElement('input');
inputNode.name = 'verwijder_dienst';
inputNode.setAttribute('type', 'button');
inputNode.setAttribute('onclick', 'delLine(this)');
inputNode.value = 'Verwijder dienst';
newCell.appendChild(inputNode);
newRow.appendChild(newCell);
document.getElementById('dienst').appendChild(newRow);
};
function delLine(line)
{
var row = line.parentNode.parentNode;
row.parentNode.removeChild(row);
};
function bereken()
{
var sumexbtw = $('.prijs').sum(function()
{
return +parseFloat(this.value) || 0;
});
$('#totaalexbtw').val(sumexbtw.toFixed(2));
var btw = sumexbtw * 0,21;
$('#btw').val(btw.toFixed(2));
var totaal = sumexbtw + btw;
$('#totaal').val(totaal.toFixed(2));
};
$(document).on('change', 'input.prijs', bereken);
</script>
</head>
<body>
<?php
include("function.php");
// haal max factuurnr op uit database
$sth1 = maakConnectie() -> prepare("SELECT MAX(factuurnummer) as 'max' FROM factuur");
$sth1 -> execute();
$result = $sth1 -> fetchAll(PDO :: FETCH_ASSOC);
// tel hier 1 bij op zodat er steeds opeenvolgende nummers worden genereerd
foreach($result as $rij)
{
$factuurnr = $rij['max'] + 1;
}
$datum = date("d-m-Y");
$sth2 = maakConnectie() -> prepare("SELECT voornaam, achternaam FROM gebruiker");
$sth2 -> execute();
$result2 = $sth2 -> fetchAll (PDO::FETCH_ASSOC);
?>
<form method="GET" action="aanmaken_factuur.php" class="formulier">
<table>
<tr>
<td>Factuur nr:</td>
<td align="right"><?php print($factuurnr);?></td>
</tr>
<tr>
<td>Datum:</td>
<td align="right"><?php print($datum);?></td>
</tr>
</table>
<br>
<table>
<tr>
<td><select name="klanten" onchange="kiesklant(this.value)">
<option value="" selected>Kies klant</option>
<?php foreach($result2 as $rij)
{
print("<option value=\"".$rij["voornaam"]." ".$rij["achternaam"]."\">".$rij["voornaam"]." ".$rij["achternaam"]."</option>");
}?>
</select>
</td>
</tr>
</table>
<div id="klantinfo">
<table>
<tr>
<td>Naam:</td>
<td></td>
</tr>
<tr>
<td>Adres:</td>
<td></td>
</tr>
<tr>
<td>Tel:</td>
<td></td>
</tr>
</table>
</div>
<br>
<table id="dienst2">
<tbody id="dienst">
<tr>
<th align="left">Dienstomschrijving</th>
<th align="left">Prijs</th>
</tr>
<tr>
<td><input style="width: 200px" type="text" name="dienstomschrijving"></td>
<td><input style="width: 100px" type="text" name="prijs" class="prijs"></td>
<td><input type="button" name="verwijder_dienst" value="Verwijder dienst" onclick="delLine(this);"/></td>
</tr>
</tbody>
<tr>
<td><input type="button" name="toevoegen_dienst" value="Voeg dienst toe" onclick="addLine();" /></td>
</tr>
</table><br>
<table id="totaal">
<tr>
<td align="right">Totaal excl. BTW</td>
<td align="center" id="totaalexbtw"></td>
</tr>
<tr>
<td align="right">BTW 21%</td>
<td align="center" id="btw"></td>
</tr>
<tr>
<td colspan=2 align="center">_________________________________________</td>
</tr>
<tr>
<td align="right">Factuur totaal</td>
<td align="center" id="totaal"></td>
</tr>
<tr>
<td align="right"><button onclick="index2.php" name="annuleren">Annuleren</button></td>
<td align="right"><input type="submit" name="submit" value="Maak factuur aan"></td>
</tr>
</table>
</form>
There are two errors in your code
$('.prijs').each.change(berekentotaalexbtw());
^^^^ ^^
No need to use each and you are not assigning the function, you are calling it.
$('.prijs').change(berekentotaalexbtw);
Since i just made the same thing yesterday:
(function($) {
$.fn.sum = function (callback) {
var sum = 0;
this.each(function () {
sum += 1 * callback.apply(this);
});
return sum;
};
})(jQuery);
this is just a helper function function so you can do: $('.prijs').sum( .... ); instead of using .each(.... )
and here's your answer
// If you do $('.prijs').change() it binds it to the currently existing elements.
// i think you are adding and deleting them dynamically, so you needed a delegated event.
function berekentotaalexbtw() {
var sum = $('.prijs').sum(function() {
// just a shorter version of all the 'isNan' stuff you got going on.
// defaults to 0 if it's NaN
return +parseFloat(this.value) || 0;
});
// Since you want it printed like a currency: use sum.toFixed(2) to format it :-)
$('#totaalexbtw').val( sum.toFixed(2) );
}
$(document).on('change','input.prijs',berekentotaalexbtw);
// and on deletion of an element: berekentotaalexbtw();

Categories

Resources