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>
Related
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.
I am using the following function in a datatables table.
function novaData(d){
var dia = d.getDate().toString();
dia = (dia.length == 1) ? '0'+dia : dia;
var mes = (d.getMonth()+1).toString();
mes = (mes.length == 1) ? '0'+mes : mes;
var ano = d.getFullYear();
return dia+"-"+mes+"-"+ano;
}
class CellDate{
constructor( start_date ){
this.date = start_date;
}
getNextDate(){
if($('#user_data tbody tr').length){
var ultima_data = $("#user_data tbody tr:first td:first").text().trim().split("-");
var ultimo_dia = +ultima_data[0];
var ultimo_mes = +ultima_data[1];
var ultimo_ano = +ultima_data[2];
this.date.setDate(ultimo_dia);
this.date.setMonth(ultimo_mes-1);
this.date.setYear(ultimo_ano);
this.date.setDate( this.date.getDate()+1);
}else{
this.date.setMonth(this.date.getMonth()+1);
this.date.setDate(1);
}
return novaData(this.date);
}
}
var DateIndexer = new CellDate(new Date(Date.now()));
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1">'+DateIndexer.getNextDate()+'</td>';
html += '<td contenteditable id="data2"></td>';
html += '<td contenteditable id="data3"></td>';
html += '<td contenteditable id="data4"></td>';
html += '<td contenteditable id="data5"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-send"></span></button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html);
});
Within the class in getNextDate, when it is true (the table already has rows), creating a new row fills the date field with the date of the next day of the last row already entered.
But if the table has no row inserted, it returns in the date field NaN-NaN-NaN, because it does not enter into the else.
If you put console.log(DateIndexer.getNextDate()); before the function $('#add').click(function(){ returns 01-08-2019.
But if put console.log(DateIndexer.getNextDate()); inside the function $('#add').click(function(){ returns NaN-NaN-NaN.
Table #user_data:
<div class="container box">
<h3 align="center">MAPA DE TRABALHO</h3>
<h5 align="center">Ajudante de Ação Direta - Turno: Manhã</h5>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" name="add" id="add" class="btn btn-info"><span class="glyphicon glyphicon-plus"></span></button>
</div>
<br />
<div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Data</th>
<th>Resp. de Turno</th>
<th>Apoio</th>
<th>Elementos ALA A</th>
<th>Elementos ALA B</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</div>
Your html has no tbody, returning null on you first execution
Try to include a tbody
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Data</th>
<th>Resp. de Turno</th>
<th>Apoio</th>
<th>Elementos ALA A</th>
<th>Elementos ALA B</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This will fix your code here:
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1">'+DateIndexer.getNextDate()+'</td>';
html += '<td contenteditable id="data2"></td>';
html += '<td contenteditable id="data3"></td>';
html += '<td contenteditable id="data4"></td>';
html += '<td contenteditable id="data5"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-send"></span></button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html); //<--- right here
});
Your condition on if need to be reviewed too, because on the first execution tbody was empty, change to this
class CellDate {
constructor(start_date) {
this.date = start_date;
}
getNextDate() {
//here the change for if condition
if ($('#user_data tbody tr') != null && $('#user_data tbody tr').length > 0) {
var ultima_data = $("#user_data tbody tr:first td:first").text().trim().split("-");
var ultimo_dia = +ultima_data[0];
var ultimo_mes = +ultima_data[1];
var ultimo_ano = +ultima_data[2];
this.date.setDate(ultimo_dia);
this.date.setMonth(ultimo_mes - 1);
this.date.setYear(ultimo_ano);
this.date.setDate(this.date.getDate() + 1);
console.log('if', this.date);
} else {
this.date.setMonth(this.date.getMonth() + 1);
this.date.setDate(1);
console.log('else', this.date);
}
return novaData(this.date);
}
}
Code here https://jsfiddle.net/nzb0tdjq/
I am using Material UI to build a website. I have append a list with data and it also has a popup on button. But the popup works only on first button click.
I want to make a new popup on every button click. Also here is a error from console.
"Uncaught DOMException: Failed to execute 'showModal' on 'HTMLDialogElement': The element already has an 'open' attribute, and therefore cannot be opened modally.
at HTMLDivElement."
Here is HTML
<div id="order">
<dialog style="width: 40%;" class="mdl-dialog">
<div class="mdl-dialog__content">
<table id="table" style="width: 100%;" class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Material</th>
<th>Quantity</th>
<th>Unit price</th>
</tr>
</thead>
<tbody style="width: 100%;" id="producttable">
</tbody>
</table>
</div>
<div class="mdl-dialog__actions">
<button type="button" class="mdl-button close">Confirm Order</button>
<button type="button" class="mdl-button">Order Shipped</button>
<button type="button" class="mdl-button">Order Delivered</button>
<button type="button" class="mdl-button">Order Canceled</button>
</div>
</dialog>
</div>
Here is JS
$("#order").append(
'<div style="padding-top:6px; padding-bottom:6px; margin-bottom: 16px;" class="card-wide mdl-card-order mdl-shadow--2dp"><h3 id="orderID" style="margin: 16px;" class="mdl-card__title-text">' +
'<a style="float: left; width: 65%;">Order ID : ' + orderid + ' </a><a style="float: right; width: 35%;">Date : ' + orderDate +
'</a></h3><div style="margin-left: 16px;"><p id="client_name" style=" font-size: 18px;"> Name - ' +
name + '</p><p id="client_email" style=" font-size: 18px;">Phone - ' + phone +
'</p><p id="client_email" style=" font-size: 18px;">Address - ' + address +
'</p></div><div class="mdl-card__menu"></div><div id="dialog" class="mdl-card__actions mdl-card--border"> <a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" onclick="purchaseList(' + orderid + ')"> Purchase List </a></div></div>');
function purchaseList(listid) {
var starCountRef = firebase.database().ref('Orders/' + listid).child('foodItems');
starCountRef.on('child_added', snapshot => {
var snaps = snapshot.val();
var itemPrice = snaps.price;
var itemName = snaps.productName;
var itemQuantity = snaps.quantity;
console.log(itemName);
$("#producttable").append(
'<tr><td class="mdl-data-table__cell--non-numeric">' + itemName + '</td><td>' + itemQuantity + '</td><td>' + itemPrice + '</td></tr>'
);
});
var dialog = document.querySelector('dialog');
var showDialogButton = document.querySelector('#dialog');
if (!dialog.showModal) {
dialogPolyfill.registerDialog(dialog);
}
showDialogButton.addEventListener('click', function () {
dialog.showModal();
});
dialog.querySelector('.close').addEventListener('click', function () {
var element = document.getElementById("producttable");
while (element.lastChild) {
element.removeChild(element.lastChild);
}
dialog.close();
});
}
Dont know if it is the point but
dialog.querySelector('.close').addEventListener(...
wont work with multiple classes. You have to use the
classList.contains('close')
for example but i would just give an id to the .close element to get it easy
<button type="button" id ="close" class="mdl-button">Confirm Order</button>
dialog.querySelector("#close");
or even better generate your HTML tag elements in JS to have direct access like
const closeBtn = document.createElement("button");
closeBtn.className = "mdl-button";
closeBtn.type = "button";
dialog.querySelector(".mdl-dialog__actions").append(closeBtn);
closeBtn.addEventListener("click", (e)=>{
//Todo on click
})
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'> ..."
In my table I have 2 rows please see my screen shot,suppose I click first check box means I want to take that id ** and **to_area value in jquery how can do this,I tried but I can not get please help some one
$(document).ready(function() {
$('#chemist_allotment_btn').click(function() {
if ($('#chemist_allotment_form').valid()) {
$.ajax({
url: 'update_chemist_bulk_transfer.php',
type: 'POST',
data: $('form#chemist_allotment_form').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data); // convert the json
console.log(res);
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function(key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td>' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td>' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
$('#SampleDT tbody').empty().append(htmlString);
$('#get_to_area').click(function() {
var id = $('input[name=getchemist]:checked').val();
if ($(".getchemist").prop('checked') == true) {
alert(id);
alert(value.to_area);
} else {
alert('Please Check');
}
});
} else {
$('#SampleDT tbody').empty().append('No Datas Found');
}
},
});
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<center>
<div class="form-group">
<button type="button" class="btn btn-primary" style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
Firstly, add classes to each <td>, like <td class='id'>[Your id]</td>
Similarly for all the elements doctor-name, to-area, etc and a class to each <tr> like row-select
Somewhat like this:
<tr class="row-select">
<td class="select">...</td>
<td class="id">...</td>
<td class="to-area">...</td>
.
.
.
</tr>
Use jQuery like this:
$('.row-select').click(function(){
var id,toArea,checkBox;
id = $(this).find('.id').html(); //get the ID field
toArea = $(this).find('.to-area').html(); //get the to-area field
checkBox = $(this).find('.select > input');
checkbox.prop('checked',!checkbox.prop('checked'));
})
This code will get you he value no mater where you click on the row, and also invert the selection on the checkbox
To get the values of rows selected when the form is submitted run a loop like this
$('.row-select input:checked').each(function(){
var id,toArea,checkBox;
id = $(this).closest('tr').find('.id').html(); //get the ID field
toArea = $(this).closest('tr').find('.to-area').html(); //get the to-area field
})
EDIT
All together:
$(document).ready(function() {
$('#btnSubmit').click(function() {
$('.row-select input:checked').each(function() {
var id, name;
id = $(this).closest('tr').find('.id').html();
name = $(this).closest('tr').find('.name').html();
alert('ID: ' + id + " | Name: " + name);
})
})
$('#btnSelectAll').click(function() {
$('.row-select input').each(function() {
$(this).prop('checked', true);
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">12</td>
<td class="name">Jones</td>
</tr>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">10</td>
<td class="name">Joseph</td>
</tr>
</table>
<button id="btnSelectAll">Select all</button>
<button id="btnSubmit">Get Value</button>
Process step-by-step:
Give the td you need some classes (from-a & to-a);
Initialize an empty array all (we'll store the data inside it later on);
Create a function that is triggered by the checkbox change
Inside the function you need to know which checkbox has changed, what's the state of it, what tr does it belong to and at the end what are the TO AREA and FROM AREA values.
If the state = checked we will add the values to the all (our small data storage);
If the state = not-checked we will remove the value from the all array;
Finally when we are done with selecting and deselecting rows by pressing the button we can get the values of the selected rows.
var all = [];
$('input[type="checkbox"]').change(function(){
var checkbox = $(this);
var state = checkbox.prop('checked');
var tr = checkbox.parents('tr');
var from = tr.children('.from-a').text();
var to = tr.children('.to-a').text();
if(state){
all.push(from + ' -> ' + to);
}else{
var index = all.indexOf(from + ' -> ' + to);
all.splice(index, 1);
}
})
$('#get_to_area').click(function(){
alert(all);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox"></td>
<td>1</td>
<td>Nick</td>
<td class="from-a">Kosur</td>
<td class="to-a">Nath Pari</td>
<td>Address</td>
</tr>
<tr id="2">
<td><input type="checkbox"></td>
<td>2</td>
<td>John</td>
<td class="from-a">Rusok</td>
<td class="to-a">iraP htaN</td>
<td>sserddA</td>
</tr>
</tbody>
</table>
<center>
<div class="form-group">
<button style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
This is just the basic concept, you can modify it to suit your needs, I'll be happy to help you if you get stuck.
You can also use this fiddle:
In JS:
$('#get_to_area').click(function () {
var id = $('input[name=getchemist]:checked').val();
if ($('input[name=getchemist]').is(':checked')) {
var ID = $('input[name=getchemist]').parent().parent().siblings('td.chkid').html();
var TO_Area = $('input[name=getchemist]').parent().parent().siblings('td.toarea').html();
}
else {
alert('Please Check');
}
});
In Html:
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function (key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td class="chkid">' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td class="toarea">' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
I'm guessing you need values of each td whose checbox are checked. This piece of code should get you started.
As you can see, Code loops through each checkbox which is checked, gets contents inside its corresponding td.
var Result = new Array();
$('.checkbox-custom input[type="checkbox"]:checked').each(function(){
var _this = $(this).closest('tr').find('td');
var id= $(_this).eq(0);
var name = $(_this).eq(1);
................... //Similar way for the others
Result.Push(id,name,....)
});