Sum dynamically generated fees - javascript

I am designing fee system where in user can define fees component and themseleves. I have managed to create facility for user to define the fee component and fee amount as per their need. But when I am trying to add them this doesnt seems to be working even though I am trying to add them by allocating class to them. Below is the html code :
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<link rel="stylesheet" href="masterfees.css" />
<title>feemaster</title>
<script type="text/javascript" src="ffees.js"></script>
<script type="text/javascript">
function totalfixfees(){
var tffees = 0;
var cusid_ele = document.getElementsByClassName('ffeetotal');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseFloat(cusid_ele[i].value)) )
tffees += parseFloat(cusid_ele[i].value);
}
document.getElementById('tffees').value=tffees;
}
</script>
<script></script>
<style>
</style>
</head>
<body>
<!-- Trigger/Open The Modal for adding fees -->
<button id="myBtn">Add New Fees</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close"><button>✖</button></span>
<h2>Create Fees</h2>
</div>
<div class="modal-body">
<fieldset>
<legend>Fixed Fees Component</legend>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<tr>
<th>Name</th>
<th>Amount (in Rs)</th>
</tr>
<tr id="row1">
<td id="ffname_row1">Annual Fees</td>
<td id="ffamount_row1" class="ffeetotal">1000</td>
<td>
<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" id="save_button1" value="Save" class="save" onclick="save_row('1')">
<input type="button" value="Delete" class="delete" onclick="delete_row('1')">
</td>
</tr>
<tr id="row2">
<td id="ffname_row2">Medical Fees</td>
<td id="ffamount_row2" class="ffeetotal">2000</td>
<td>
<input type="button" id="edit_button2" value="Edit" class="edit" onclick="edit_row('2')">
<input type="button" id="save_button2" value="Save" class="save" onclick="save_row('2')">
<input type="button" value="Delete" class="delete" onclick="delete_row('2')">
</td>
</tr>
<tr id="row3">
<td id="ffname_row3">Tution Fees</td>
<td id="ffamount_row3" class="ffeetotal">3000</td>
<td>
<input type="button" id="edit_button3" value="Edit" class="edit" onclick="edit_row('3')">
<input type="button" id="save_button3" value="Save" class="save" onclick="save_row('3')">
<input type="button" value="Delete" class="delete" onclick="delete_row('3')">
</td>
</tr>
<tr>
<td><input type="text" id="new_ffname"></td>
<td><input type="number" id="new_ffamount" class="ffeetotal"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</table>
</div>
<br>
<label> Fixed Fee Total </label>
<input name="tffees" type="text" id="tffees" class="n1fees" value="" readonly>
<button onclick="totalfixfees()">Calculate Total Fees</button>
</div>
<div class="modal-footer">
<h3></h3>
</div>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
The javascript is
function edit_row(no)
{
document.getElementById("edit_button"+no).style.display="none";
document.getElementById("save_button"+no).style.display="block";
var ffname=document.getElementById("ffname_row"+no);
var ffamount=document.getElementById("ffamount_row"+no);
var ffname_data=ffname.innerHTML;
var ffamount_data=ffamount.innerHTML;
ffname.innerHTML="<input type='text' id='ffname_text"+no+"' value='"+ffname_data+"'>";
ffamount.innerHTML="<input type='number' class='ffeetotal' id='ffamount_text"+no+"' value='"+ffamount_data+"'>";
}
function save_row(no)
{
var ffname_val=document.getElementById("ffname_text"+no).value;
var ffamount_val=document.getElementById("ffamount_text"+no).value;
document.getElementById("ffname_row"+no).innerHTML=ffname_val;
document.getElementById("ffamount_row"+no).innerHTML=ffamount_val;
document.getElementById("edit_button"+no).style.display="block";
document.getElementById("save_button"+no).style.display="none";
}
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row()
{
var new_ffname=document.getElementById("new_ffname").value;
var new_ffamount=document.getElementById("new_ffamount").value;
var table=document.getElementById("data_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+table_len+"'><td id='ffname_row"+table_len+"'>"+new_ffname+"</td><td id='ffamount_row"+table_len+"'>"+new_ffamount+"</td><td><input type='button' id='edit_button"+table_len+"' value='Edit' class='edit' onclick='edit_row("+table_len+")'> <input type='button' id='save_button"+table_len+"' value='Save' class='save' onclick='save_row("+table_len+")'> <input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'></td></tr>";
document.getElementById("new_ffname").value="";
document.getElementById("new_ffamount").value="";
}
I am not sure where I am going wrong. Can you please help me ?
Thanks

You have to add the ffeetotal class to the newly added td in add_row function. Use this fiddle:
JS:
function totalfixfees(){
var tffees = 0;
var cusid_ele = document.getElementsByClassName('ffeetotal');
//debugger;
for (var i = 0; i < cusid_ele.length; i++) {
if (!isNaN(parseFloat(cusid_ele[i].innerText)) )
tffees += parseFloat(cusid_ele[i].innerText);
}
document.getElementById('tffees').innerText = tffees;
}
function add_row() {
var new_ffname = document.getElementById("new_ffname").value;
var new_ffamount = document.getElementById("new_ffamount").value;
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='ffname_row" + table_len + "'>" + new_ffname + "</td><td class='ffeetotal' id='ffamount_row" + table_len + "'>" + new_ffamount + "</td><td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'> <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> <input type='button' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_ffname").value = "";
document.getElementById("new_ffamount").value = "";
}

You are reading the value property for retrieving the fees, but these elements are not input elements, but td elements, which don't have a value property.
Instead use textContent:
function totalfixfees(){
var tffees = 0;
var cusid_ele = document.getElementsByClassName('ffeetotal');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseFloat(cusid_ele[i].textContent)) )
tffees += parseFloat(cusid_ele[i].textContent);
}
document.getElementById('tffees').value=tffees;
}
Make sure to also add the class ffeetotal to the relevant td elements when you insert new rows. So change accordingly the following assignment:
var row = table.insertRow(table_len).outerHTML="...
.. so it has the class mentioned in this part:
"... <td id='ffamount_row"+table_len+"' class='ffeetotal'> ..."

Related

Dynamically add row with jQuery

I have an application that integrated with barcode scanner, like this:
I have made a row dynamically with this snippet of code:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
<h1 align="center">
Barcode: <br><input type="text" id="myHeader" value="5555">
</h1>
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
and here is the code that I wrapped with script tag:
<script >
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" disabled value="123123123" class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
} </script>
But the code above just add the row only when I clicked the Add Row button.
What I want for now is, when I scan a barcode with a barcode scanner, the row automatically added follow the scanned barcode result.
In this case it will be: "When the value on barcode on the header changed ( <h1 align="center">Barcode: 123123123</h1> , the result is same when I clicked the Add Row button.
So, please refer any approach, tutorial or example code how to do that, it would be very appreciated :)
For additional information: The purpose of this app is for cashier app on a store, like when the cashier scan a product, the result automatically appear on the app. And I developing it using Python Flask.
You have to listen to the changes made in the element. You can try with MutationObserver
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" disabled value="123123123" class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
// Listen to the changes in the header element and add row
var target = document.querySelector('#myHeader');
setTimeout(function() {
target.textContent = "New Barcode: XXXXXXXXX"; // change text after 2 seconds
}, 2000)
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
$("#addrow").trigger("click"); // trigger the click event to add row if the header text is changed
});
});
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
// otherwise
observer.disconnect();
observer.observe(target, config);
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
<h1 align="center" id="myHeader">Barcode: 123123123</h1>
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
Update: The updated question indicates that you can trigger the click event on blur event of the barcode input element:
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
var barcode = $("#myHeader").val().trim();// take the current barcode value
cols += '<td><input type="text" disabled value= '+ barcode +' class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
// Add new row by triggering the click event on focus out
var target = document.querySelector('#myHeader');
target.addEventListener('blur', function(){
$("#addrow").trigger("click");
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
Barcode: <br><input type="text" id="myHeader" value="5555">
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
$('#myTable tbody').append(newRow)
I think you have problem with your jQuery selector.
Try the code shown above - hope it works for you.

Add a blank row in HTML Table

I have an HTML table that adds a new row below where the button in current row is located. Currently when the row is created it generates a clone of the row above including the data. I would like this to be a row that has no entry for the input values rather than a clone of the values above.
Javascript
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
after you add a row, you can just set the values of all inputs in that row to "". get all the inputs of type text using tr.querySelectorAll("input[type='text']") and using a loop set values of all to ""
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for(var i=0; i<inputs.length; i++)
inputs[i].value = "";
}
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
You can do this very easily with jQuery:
var $lastRow = $("table#Table tr:last-child");
var $newRow = $lastRow.clone()
$newRow.find("input[type=text]").val(''); //empty all the values in text inputs
$("table#Table").append( $newRow );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
Add this line of code to your function to empty values in HTML code:
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.innerHTML = tr.innerHTML.replace(/value='.*'/, "value=''"); //this will remove all values from your html
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
Using JQuery:
function addRow(){
var t = $("#Table tr").last().clone();
t.find("input").each(function(i,element) {
$(element).val("");
});
t.appendTo("#Table");
}
I can suggest you do this - define table rows in javascript and add those directly. Also, use th for table headers
function edit_row(no) {
document.getElementById("edit_button" + no).style.display = "none";
document.getElementById("save_button" + no).style.display = "block";
// get elements
var measured = document.getElementById("measured_row" + no);
var inclination = document.getElementById("inclination_row" + no);
var azimuth = document.getElementById("azimuth_row" + no);
// get their values
var measured_data = measured.innerHTML;
var inclination_data = inclination.innerHTML;
var azimuth_data = azimuth.innerHTML;
// replace by editable input tags
measured.innerHTML = "<input type='text' id='measured_text" + no + "' value='" + measured_data + "'>";
inclination.innerHTML = "<input type='text' id='inclination_text" + no + "' value='" + inclination_data + "'>";
azimuth.innerHTML = "<input type='text' id='azimuth_text" + no + "' value='" + azimuth_data + "'>";
}
function save_row(no) {
// same as in edit function
var measured_val = document.getElementById("measured_text" + no).value;
var inclination_val = document.getElementById("inclination_text" + no).value;
var azimuth_val = document.getElementById("azimuth_text" + no).value;
document.getElementById("measured_row" + no).innerHTML = measured_val;
document.getElementById("inclination_row" + no).innerHTML = inclination_val;
document.getElementById("azimuth_row" + no).innerHTML = azimuth_val;
document.getElementById("edit_button" + no).style.display = "block";
document.getElementById("save_button" + no).style.display = "none";
}
function delete_row(no) {
document.getElementById("row" + no + "").outerHTML = "";
}
function add_row() {
var new_measured = document.getElementById("new_measured").value;
var new_inclination = document.getElementById("new_inclination").value;
var new_azimuth = document.getElementById("new_azimuth").value;
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='measured_row" + table_len + "'>" + new_measured + "</td><td id='inclination_row" + table_len + "'>" + new_inclination + "</td><td id='azimuth_row" + table_len + "'>" + new_azimuth + "</td><td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'> <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> <input type='button' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_measured").value = "";
document.getElementById("new_inclination").value = "";
document.getElementById("new_azimuth").value = "";
}
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<tr>
<th>Measured Depth</th>
<th>Inclination</th>
<th>Azimuth</th>
</tr>
<tr id="row1">
<td id="measured_row1">339</td>
<td id="inclination_row1">0.540000021</td>
<td id="azimuth_row1">310.7200012</td>
<td>
<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" id="save_button1" value="Save" class="save" onclick="save_row('1')">
<input type="button" value="Delete" class="delete" onclick="delete_row('1')">
</td>
</tr>
<tr>
<td><input type="text" id="new_measured"></td>
<td><input type="text" id="new_inclination"></td>
<td><input type="text" id="new_azimuth"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</table>

How to call a php ajax/function on a html button click

I tried to include inside my page a script to add a dynamic row and every time I click on add, it save the data in database.
The problem is when I insert the data and click on add row, doesn't work.
How to write correctly this element?
<div class="mainTitle">Write a customer question : Intent</div>
<div class="adminformTitle">
<div class="form-group form-group-options col-md-12">
';
$content .= '
<table id="myTable" class="table table-sm table-hover order-list">
<thead>
<tr>
<td>User Question</td>
<td>Language</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-9">
' . HTML::inputField('user_question', null, 'placeholder="Write a short answer"'). '
</td>
<td class="col-md-2">
' . HTML::inputField('language', null, 'placeholder="Language"'). '
</td>
<td class="col-sm-1"><a id="delete_row" class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
';
the script ::
On click, it add a new row and save / delete data in function
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="user_question' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="language' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
// call files
$.ajax({
type: 'POST',
url: 'ajax.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
});
</script>

Can't add data to table with plain JS

function addData() {
var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>New task:
<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>
<h3>Task Table</h3>
<div id="excell">
<table id="table" cellspacing="0px" cellpadding="25px" text-align="center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
I'm learning Javascript and I'm trying to implement a small "ID and Task" table, but somehow it only works when I enter only 1 type of data such as only ID or only task, when I enter 2 data at the same time, nothing happens. I'd be grateful if you tell me what is the problem and how can I fix it. Thank you.
Here's my HTML
<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>
New task:<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>
<h3>Task Table</h3>
<div id = "excell">
<table id = "table" cellspacing = "0px" cellpadding = "25px" text-align = "center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
and here's my JS
function addData() {
var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
Actual problem with your code is, you have used Submit button. Normally when a submit button is hit it post the data to action property of the form tag, which means transfer the page to next; if action property is not given, it give flickering effect and stay with current page and made all components with empty. The same is happen in your code also.
Better Change the code
<input type="Submit" value="Add" onClick="addData();"/>
into
<input type="BUTTON" value="Add" onClick="addData();"/>
and try its worked fine.

Dynamically creating buttons with popovers

I try to create buttons with popovers via JS dynamically. So far so good but I can't make it to get Div content attached to the popovers. They show up if I press the button but except of the headline they are just empty. Therefore I guess the problem lies in the //Append newDiv to Popovercontent - Part. But exactly with this function I am able to append div boxes to my popovers statically.
HTML:
<table id="table">
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
<tr>
<td></td>
<td>
<div id="div" style="display:none">
<input type="checkbox"> Label 1</input><br>
<input type="checkbox"> Label 2</input>
</div>
</td>
<td style="text-align: center; vertical-align: middle;">
<button data-toggle="popover" id="btn1" data-original-title="Popover" data-html="true" data-placement="bottom" type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span>
</button>
</td>
</tr>
</table>
JS:
$("#btn1").popover({
html: true,
content: function() {
return $("#div").html();
}
});
var id = 2;
function addButton() {
//Creating HTML-Code for popovers
var newHTML = "<div style='display:none' id = 'newDiv" + id + "'>";
for (i = 0; i < 2; i++) {
newHTML += "<input type=\"checkbox\" name=\"name" + id + i + "\">Label" + i + "</input><br>";
}
newHTML += "</div><button data-toggle=\"popover\" id=\"btn" + id + "\" data-original-title=\"Popover\" data-html=\"true\" data-placement=\"bottom\" type=\"button\" class=\"btn btn-default\" aria-label=\"Left Align\">";
newHTML += "<span class=\"glyphicon glyphicon-chevron-down\" aria-hidden=\"true\"></span></button>";
//Creating new Element
var trhtml = document.getElementById("table").insertRow();
var tdhtml = document.createElement("td");
tdhtml.style = "text-align: center; vertical-align: middle;";
tdhtml.innerHTML = newHTML;
trhtml.appendChild(tdhtml);
//Initialize new Popover
$('[data-toggle="popover"]').popover();
//Append newDiv to Popovercontent
$("#btn" + id).popover({
html: true,
content: function() {
return $("#newDiv" + id).html();
}
});
id=id+1;
}
Thank you very much!
You are facing this problem because are binding id inside popover content callback and then you are using variable id to create jquery selector $("#newDiv" + id).html()
But the id variable is incremented each time, When the actual popover event called it receive id value NoOfRowInTable+1 for all popover content function calllback.
For example if you have called addButton() 2 time the value of id inside popover content callback will be revived as 4 for all popover content callback function.
You can find a better explanation here
JavaScript closure inside loops – simple practical example
Although for your example you don't need to make a hidden div with some id
you can create html String for checkboxes and then add it to popover content callback .
Here is working demo
EDIT : Use .bind() to bind id properly
$("#btn1").popover({
html: true,
content: function() {
return $("#div").html();
}
});
var id = 2;
$("#btn1").popover({
html: true,
content: function() {
return $("#div").html();
}
});
var id = 2;
function addButton() {
//Creating HTML-Code for popovers
var newHTML = "<div style='display:none' id = 'newDiv" + id + "'>";
for (i = 0; i < 2; i++) {
newHTML += "<input type=\"checkbox\" name=\"name" + id + i + "\">Label" + i + "</input><br>";
}
newHTML += "</div><button data-toggle=\"popover\" id=\"btn" + id + "\" data-original-title=\"Popover\" data-html=\"true\" data-placement=\"bottom\" type=\"button\" class=\"btn btn-default\" aria-label=\"Left Align\">";
newHTML += "<span class=\"glyphicon glyphicon-chevron-down\" aria-hidden=\"true\"></span></button>";
//Creating new Element
var trhtml = document.getElementById("table").insertRow();
//add empty first empty column
var tdhtml0 = document.createElement("td");
trhtml.appendChild(tdhtml0);
var tdhtml1 = document.createElement("td");
tdhtml1.style = "text-align: center; vertical-align: middle;";
tdhtml1.innerHTML = newHTML;
trhtml.appendChild(tdhtml1);
//Append newDiv to Popovercontent
$("#btn" + id).popover({
html: true,
content: function(id) {
return $("#newDiv" + id).html();
}.bind(this, id)
});
id = id + 1;
}
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<table id="table" class="table">
<tr>
<th>Col 1</th>
<th>Col 2</th>
</tr>
<tr>
<td>
<div id="div" style="display:none">
<input type="checkbox">Label 1
<br>
<input type="checkbox">Label 2
</div>
</td>
<td style="text-align: center; vertical-align: middle;">
<button data-toggle="popover" id="btn1" data-original-title="Popover" data-html="true" data-placement="bottom" type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span>
</button>
</td>
</tr>
</table>
<button onclick="addButton()">Add Row</button>

Categories