This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I am facing problem in $(.class).click(function(){}); which is not working with my code.
Can any one help me on this.
My code is:
whenever i click on edit button popup div open but since click event not fire so text boxes in popup not filled due to which i am not able to update the record.
Please help me to resolve the issue:
$(document).ready(function(){
$(".btn-ed").click(function(e) {
try{
var $row = $(this).closest("tr");
var id = $row.find('td:eq(0)').text();
var className = $row.find('td:eq(1)').text();
var schoolName = $row.find('td:eq(2)').text();
var status = $row.find('td:eq(3)').text();
$("#txtId").val(id);
$("#txtClass").val(className);
$("#txtSchool").val(schoolName);
$("#ddlStatus").val((status=='Active'?'1':'0'));
}
catch(err){alert(err);}
});
$("#btnUpdate").click(function() {
var id = $('#txtId').val();
var status = $("#ddlStatus").val();
$.ajax({
cache: false,
type:"post",
url:"updateClass.php",
data: {cId: id, cStatus: status},
success:function(ret){
if(ret=='1')
{
location.reload(true);
window.location="?u=1&#close";
}
else
{
location.reload(true);
window.location="?u=0&#close";
}
}
});
});
});
$(document).ready(function(){
try{
getClassData();
var res = GetParameterValues('u');
var res1='';
if(res)
{
res1 = res.split('#')[0];
if(res1=='1')
{
$("#msg-inf").hide();
$("#msg-fail").hide();
$("#msg-sucess").show();
}
else
{
$("#msg-inf").hide();
$("#msg-fail").show();
$("#msg-sucess").hide();
}
}
}
catch(er){alert(er);}
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
function getClassData(){
$.ajax({
cache: false,
type:"post",
url:"classdata.php",
datatype: 'json',
data: {qry: 'ClassData'},
success:function(ret){
var jobj = $.parseJSON(ret);
loadTable(jobj);
}
});
}
function loadTable(dt){
try{
var dLength = dt.length;
var tableData = '';
if(dLength > 0){
for(var i=0;i < dLength; i++){
tableData += "<tr class='data'><td class='data' width='30px'>"+dt[i].id+"</td><td class='data' width='70px'>"+dt[i].class_name+"</td><td class='data' width='70px'>"+dt[i].school_name+"</td><td class='data' width='60px'>"+(dt[i].is_active=='1'?'Active':'Deacive')+"</td><td class='data' width='70px'><a href='#openModal'><button id='button' class='btn-ed'>Edit</button></a></td></tr>";
}
$("#tblClass").append(tableData).show();
}
}
catch(err){alert(err);}
}
});
and HTML
<body>
<?php
include 'header.php';
?>
<div id="wrapper">
<?php include 'left-sidebar.php'; ?>
<div id="rightContent">
<h3>Classes</h3>
<div><div class='informational' id="msg-inf">To update status of any class click on Edit button.</div>
<div class='failure' id="msg-fail" style="display:none;">Class status changing failed due to some error.</div>
<div class='success' id="msg-sucess" style="display:none;">Class status successfully changed. Reload page to view changes</div>
</div>
<table class="data" id="tblClass" style="display:none;">
<tr class="data">
<th class="data" width="30px">No</th>
<th class="data" width="70px">Class Name</th>
<th class="data" width='70px'>School Name</th>
<th class="data" width='60px'>Status</th>
<th class="data" width="70px">Action</th>
</tr>
<!--<tr class="data">
<td class="data" width="30px"><?php echo $row['id'];?></td>
<td class="data" width="70px"><?php echo $row['class_name'];?></td>
<td class="data" width="70px"><?php echo $row['school_name'];?></td>
<td class="data" width="60px"><?php echo $status;?></td>
<td class="data" width="70px">
<button id="button" class="btn-ed">Edit</button>
</td>
</tr>-->
</table>
</div>
<div class="clear"></div>
<!-- modal dialog div --->
<div id="openModal" class="modalDialog">
<div> X
<h2>Update Class Status</h2>
<div style="text-align:center;">
<table width="100%">
<tr>
<td>Id</td>
<td><input type="text" id="txtId" disabled="true"></td>
</tr>
<tr>
<td>Class:</td>
<td><input type="text" id="txtClass" disabled="true"></td>
</tr>
<tr>
<td>School</td>
<td><input type="text" id="txtSchool" disabled="true"></td>
</tr>
<tr>
<td>Status</td>
<td><select id="ddlStatus"><option value="1">Active</option><option value="0">Deactive</option></select></td>
</tr>
<tr><td></td>
<td>
<button id="btnUpdate" class="button">Update</button>
Cancel
</td>
</tr>
</table>
</div>
</div>
</div>
Thanks in advance..
When dynamically adding an element to the DOM, you cannot attach an event handler to it on document.ready. You need to redefine you event handler to the document, and "look" for the element instead.
The handler should be:
$(document).on('click', '.btn-ed', function(e) {
try{
var $row = $(this).closest("tr");
var id = $row.find('td:eq(0)').text();
var className = $row.find('td:eq(1)').text();
var schoolName = $row.find('td:eq(2)').text();
var status = $row.find('td:eq(3)').text();
$("#txtId").val(id);
$("#txtClass").val(className);
$("#txtSchool").val(schoolName);
$("#ddlStatus").val((status=='Active'?'1':'0'));
}
catch(err){alert(err);}
});
You can try this:
$(document.body).on('click', '.btn-ed' ,function(e){
// your code
});
Related
When I click on my button "Select" it should show me the HTML popup, and for some reason is not happening.
Could it be some id problem or hard code?
The main idea is to click and bring some kind of list reading from a random array list.
Below: my .js with the call back id and display.
Any ideas?
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display: none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none">
<div class="popuptitle" id="details-name"></div>
<table width="100%" id="detailsgrid">
<tr>
<td style="text-align:left">Start Time</td>
<td> <select id="details-startTime" data-role="none"></select></td>
</tr>
<tr>
<td style="text-align:left">End Time</td>
<td> <select id="details-endTime" data-role="none"></select></td>
</tr>
</table>
<div>
<button class="smallButton" onClick="closeProjectPopup()">Cancel</button>
<button class="smallButton" onClick="submitProjectPopup()">Submit</button>
</div>
</div>
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
Javascript code:
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = i;
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: '',
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to show the popup
$('#projectPopUp').show();
//to close the popup
$('#projectPopUp').hide();
$(document).ready(function() {
buildQuestionnaire();
});
My problem is that the edit function will display undefined in input field but in my console it displays the img url..
Can you please correct my script why it displays undefined
This is my js code, where I created 3 function,the , and
my.js
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row(){
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
if (new_image&&new_title&&new_description != "") {
var table=document.getElementById("data_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML=
"<div id='row"+table_len+"'><img id='image_row"+table_len+"' src = "+new_image+"><div id='title_row"+table_len+"'>"+new_title+
"</div><div id='description_row"+table_len+"'>"+new_description+"</div><div><input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'><input type='button' value='Edit' class='edit' onclick='edit_row("+table_len+")'></div></div>";
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
}
function edit_row(no){
var image=document.getElementById("image_row"+no).getAttribute("src");
console.log(image);
var title=document.getElementById("title_row"+no);
console.log(title);
var description=document.getElementById("description_row"+no);
console.log(description);
var image_data = image.innerHTML;
var title_data = title.innerHTML;
var description_data =description.innerHTML;
document.getElementById("new_image").value=image_data;
document.getElementById("new_title").value=title_data;
document.getElementById("new_description").value=description_data;
}
This part is my html code, why I only have div and tables
index.html
<div id="wrapper">
<h1 align="center">My Todo App</h1>
<div id="container">
<form id="myForm">
<table align='center' cellspacing=2 cellpadding=5>
<tr>
<th>Image Link</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td><input type="text" id="new_image"></td>
<td><input type="text" id="new_title"></td>
<td><input type="text" id="new_description"></td>
<td><input type="button" class="add" onclick="add_row();" value="SAVE"></td>
</tr>
</table>
</form>
</div>
<div id="content_container">
<div>
<table align='center' cellspacing=2 cellpadding=5 id="data_table">
</table>
</div>
</div>
</div>
and also how to append the new edited data when clicking the save button, in my case it will add another row.
Remove image.innerHTML inside function edit_row(no)
Added new function as per your question
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row(){
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
if (new_image&&new_title&&new_description != "") {
var table=document.getElementById("data_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML=
"<div class='myrow'><div id='row"+table_len+"'><img id='image_row"+table_len+"' src = "+new_image+"><div id='title_row"+table_len+"' class='titleData'>"+new_title+
"</div><div class='descData' id='description_row"+table_len+"'>"+new_description+"</div><div><input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'><input type='button' value='Edit' class='edit' onclick='edit_row("+table_len+",this)'></div></div></div>";
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
}
function edit_row(no,ref){
ref.value="Save";
ref.removeAttribute("onclick");
var image=document.getElementById("image_row"+no).getAttribute("src");
console.log(image);
var title=document.getElementById("title_row"+no);
console.log(title);
var description=document.getElementById("description_row"+no);
console.log(description);
var image_data = image; // remove image.innerHTML
var title_data = title.innerHTML;
var description_data =description.innerHTML;
document.getElementById("new_image").value=image_data;
document.getElementById("new_title").value=title_data;
document.getElementById("new_description").value=description_data;
ref.setAttribute("onclick","saveEdit(this,'"+no+"')");
}
function saveEdit(ref,no)
{
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
var parent= (ref.parentElement).parentElement;
var img=parent.firstChild.setAttribute("src",new_image);
var list = document.getElementById(parent.id);
var title=list.getElementsByClassName("titleData")[0];
var desc=list.getElementsByClassName("descData")[0];
title.innerHTML=new_title;
desc.innerHTML=new_description;
ref.value="Edit";
ref.removeAttribute("onclick");
ref.setAttribute("onclick","edit_row("+no+",this)");
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
<div id="wrapper">
<h1 align="center">My Todo App</h1>
<div id="container">
<form id="myForm">
<table align='center' cellspacing=2 cellpadding=5>
<tr>
<th>Image Link</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td><input type="text" id="new_image"></td>
<td><input type="text" id="new_title"></td>
<td><input type="text" id="new_description"></td>
<td><input type="button" class="add" onclick="add_row();" value="SAVE"></td>
</tr>
</table>
</form>
</div>
<div id="content_container">
<div>
<table align='center' cellspacing=2 cellpadding=5 id="data_table">
</table>
</div>
</div>
</div>
I wanted to create a simple html select-all checkbox for my table form. So when we click on top of corresponding column list all the elements in the column are selected without checking other columns.
Here is what i tried..
<form name="checkn" id="frm1" class="form1" method="post">
<table class="table" cellspacing="10" border="1" style="width:100%;">
<thead>
<tr>
<th>Products List</th>
<th>
Product Available
<input type='checkbox' name='checkall' onclick='checkAll(frm1);'>
</th>
<th>
Description
<input type='checkbox' name='checkall' onclick='checkdAll(frm2);'>
</th>
</tr>
</thead>
<tbody>
<?php
//fetch data php code
?>
<tr> <td width="20%;"> <h3> <?=$products?> </h3> </td>
<td width="20%;"> <input id="frm1" type="checkbox" name="product1" value='<?=$fieldname?>' > Product Available </td>
<td width="20%;"> <input id="frm2" type="checkbox" name="product2"> Description </td>
</tr>
<button type="submit" name="submit" style="position:absolute; bottom:0;"> Submit </button>
<script type="text/javascript">
checked = false;
function checkAll (frm1)
{
var aa= document.getElementById('frm1'); if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
<script type="text/javascript">
checked = false;
function checkdAll (frm2)
{
var aa= document.getElementById('frm2'); if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
</tbody>
</table>
</form>
Please help me
I think you need to find all tr length then find td with input. after that, you can check all. Like this here is my code. I hope it helps you.
$('#IsSelectAll').on('change', function () {
if ($(this).is(':checked')) {
$('#tbCustomerList tbody tr:visible').filter(function () {
$(this).find('td:eq(1)').children('label').children('input[type=checkbox]').prop('checked', true);
});
}
else {
$('#tbCustomerList tbody tr:visible').filter(function () {
$(this).find('td:eq(1)').children('label').children('input[type=checkbox]').prop('checked', false);
});
}
});
I'm cloning a row and I want to check in the database if the code exists. This all works fine on the first row but not on the cloned rows. I have an idea that I have to make the id of the field unique, I have tried to add the the code that checks if the code exist to the add button event but it doesn't work. Can someone please tell me how to merge the two script so it works on the cloned rows.
Code:
HTML
<table>
<tr id="show_codes">
<td colspan="2" class="text-fields" align="center" valign="middle">
<div class="codeForm">
<table class="codeForm" align="left" width="500px" cellpadding="0" style="padding-left: 20px;" cellspacing="0">
<tr>
<td height="15px">Codes that exist is 0011, 1234</td>
</tr>
<tr class="code_row">
<td class="details-border1" height="40px" valign="middle" bgcolor="#f3f3f3" align="center">
<input id="code" value="" class="text ui-widget-content ui-corner-all" type="text" name="code[]" />
<div id="status"></div>
</td>
<td class="details-border2" bgcolor="#f3f3f3" align="center">
<input value="" class="text ui-widget-content ui-corner-all" type="text" name="value[]" />
</td>
<td class="borders-right-bottom" bgcolor="#f3f3f3" align="center">
<input type="button" class="btnDeleteCode" value="Delete" />
</td>
</tr>
</table>
</div>
<table width="500px" align="left">
<tr>
<td align="right"><span style="cursor: pointer; color: #007FC6; font-weight: bold;" id="btnAddCode" value="add more">Add another code</span>
</td>
</tr>
</table>
</td>
</tr>
JQUERY
var dom = {};
dom.query = jQuery.noConflict(true);
dom.query(document).ready(function () {
var clonedRow = dom.query('.code_row').clone().html();
var appendRow = '<tr class = "code_row">' + clonedRow + '</tr>';
var counter = 0;
dom.query('#btnAddCode').click(function () {
dom.query('.codeForm tr:last').after(appendRow);
counter++;
$('.codeForm tr:last input[type="text"]').attr('id', 'code[' + counter + ']');
$('.codeForm tr:last').find('input').val('');
});
dom.query('.btnDeleteCode').live('click', function () {
var rowLength = dom.query('.code_row').length;
if (rowLength > 1) {
deleteRow(this);
} else {
dom.query('.codeForm tr:last').after(appendRow);
deleteRow(this);
}
});
function deleteRow(currentNode) {
dom.query(currentNode).parent().parent().remove();
}
});
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
pic2 = new Image(16, 16);
pic2.src = "tick.gif";
dom.query(document).ready(function () {
dom.query("#code").change(function () {
var usr = dom.query("#code").val();
if (usr.length >= 4) {
dom.query("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
alert(usr);
dom.query.ajax({
type: "POST",
url: "setup_practice_preference_check_code.php",
data: "username=" + usr,
success: function (msg) {
dom.query("#status").ajaxComplete(function (event, request, settings) {
if (msg == 'OK') {
dom.query("#code").removeClass('object_error'); // if necessary
dom.query("#code").addClass("object_ok");
dom.query(this).html(' <img src="tick.gif" align="absmiddle">');
} else {
alert('msg');
dom.query("#code").removeClass('object_ok'); // if necessary
dom.query("#code").addClass("object_error");
dom.query(this).html(msg);
}
});
}
});
} else {
dom.query("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
dom.query("#code").removeClass('object_ok'); // if necessary
dom.query("#code").addClass("object_error");
}
});
});
Fiddle
Thanks
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();