Can't seem to get the simply math formula for reconcile to equal zero.
Here is the function that I am using. Using simple number to test this out and it is not working.
startbalance 0.00, endbalance 200.00, vals 200.00 = two entries +100 and +100, chg 0.00, endBal should equal 0 however it keeps coming up with a positive 200.
function addRecon(item){
var checkboxes = document.getElementsByName('deposit[]');
var vals = 0;
var invSelect1 = "";
for (var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked)
{
vals = vals + parseFloat(checkboxes[i].value);
invSelect1 += ","+checkboxes[i].id;
}
}
document.getElementById('curDeposits').innerHTML = '$ '+vals.toFixed(2);
var checkboxes = document.getElementsByName('withdrawl[]');
var chg = 0;
var invSelect2 = "";
for (var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked)
{
chg = chg + parseFloat(checkboxes[i].value);
invSelect2 += ","+checkboxes[i].id;
}
}
document.getElementById('curWithdrawls').innerHTML = '$ '+chg.toFixed(2);
var startBalance = document.getElementsByName('startbalance').value;
var endBalance = document.getElementsByName('endbalance').value;
startBalance = ~~parseFloat(startBalance);
endBalance = ~~parseFloat(endBalance);
var balEnd = 0;
balEnd = startBalance + vals - chg - endBalance;
document.getElementById('curBal').innerHTML = '$ '+balEnd.toFixed(2);
}
<div class="x_panel">
<div class="x_title">
<div class="row">
<h2>Reconcile</h2>
</div>
<div class="row">
<div class="col-xs-3">
<label>Start Balance</label>
<h3><?=number_money($startbalance);?></h3>
</div>
<div class="col-xs-3">
<label>Deposits</label>
<h3 id="curDeposits"><?=number_money(0.00);?></h3>
</div>
<div class="col-xs-3">
<label>Withdrawls</label>
<h3 id="curWithdrawls"><?=number_money(0.00);?></h3>
</div>
<div class="col-xs-3">
<label>Ending Balance</label>
<h3 id="endBalance"><?=number_money($endbalance);?></h3>
</div>
<div class="col-xs-3">
<label>Reconcile Balance</label>
<h3 id="curBal"><?=number_money($startbalance-$endbalance)?></h3>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="x_content">
<? //print_r($frm); ?>
<form action="reconcile.php" method="POST" id="reconForm">
<input type="hidden" name="mode" value="complete" id="mode" />
<input type="hidden" name="userID" value="<?=$userID?>" />
<input type="hidden" name="co" value="<?=$co?>" />
<input type="hidden" name="account" value="<?=$account;?>" />
<input type="hidden" name="startbalance" value="<?=$startbalance;?>" />
<input type="hidden" name="startdate" value="<?=$startdate;?>" />
<input type="hidden" name="endbalance" value="<?=$endbalance;?>" />
<input type="hidden" name="enddate" value="<?=$enddate;?>" />
<input type="hidden" name="debitAdd" value="" id="debitAdd"/>
<script>
function addRecon(item){
var checkboxes = document.getElementsByName('deposit[]');
var vals = 0;
var invSelect1 = "";
for (var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked)
{
vals = vals + parseFloat(checkboxes[i].value);
invSelect1 += ","+checkboxes[i].id;
}
}
document.getElementById('curDeposits').innerHTML = '$ '+vals.toFixed(2);
var checkboxes = document.getElementsByName('withdrawl[]');
var chg = 0;
var invSelect2 = "";
for (var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked)
{
chg = chg + parseFloat(checkboxes[i].value);
invSelect2 += ","+checkboxes[i].id;
}
}
document.getElementById('curWithdrawls').innerHTML = '$ '+chg.toFixed(2);
var startBalance = document.getElementsByName('startbalance').value;
var endBalance = document.getElementsByName('endbalance').value;
startBalance = ~~parseFloat(startBalance);
endBalance = ~~parseFloat(endBalance);
var balEnd = 0;
balEnd = startBalance + vals - chg - endBalance;
document.getElementById('curBal').innerHTML = '$ '+balEnd.toFixed(2);
}
</script>
<div class="">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2><i class="fa fa-clipboard"></i> Reconcile Account: <?=$account;?> <small></small></h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div class="" role="tabpanel" data-example-id="togglable-tabs">
<ul id="myTab" class="nav nav-tabs bar_tabs" role="tablist">
<li role="presentation" class="active">Deposits
</li>
<li role="presentation" class="">Withdrawls
</li>
</ul>
<div id="myTabContent" class="tab-content">
<div role="tabpanel" class="tab-pane fade active in" id="tab_content1" aria-labelledby="home-tab">
<table id="datatable-keytable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Date</th>
<th>Ref</th>
<th>Description<i class="fa fa-sort-amount-asc pull-right"></i></th>
<th>Amount</th>
<th><i class="fa fa-caret-down"></i></th>
</tr>
</thead>
<? //print_r($deposit);
echo "endbalance:".$endbalance;
echo "startbalance:".$startbalance;
for($a=0;$a<count($deposit); $a++){ ?>
<tr>
<td><?=retrieve_date($deposit[$a]['enterdate']);?></td>
<td><?=$deposit[$a]['reference'];?></td>
<td><?=$deposit[$a]['memo'];?></td>
<td><?=number_money($deposit[$a]['debit']);?></td>
<td><input type="checkbox" name="deposit[]" id="<?=$deposit[$a]['transid'];?>" value="<?=$deposit[$a]['debit'];?>" onclick="addRecon(this);"/></td>
</tr>
<? } ?>
</table>
</div>
<div role="tabpanel" class="tab-pane fade" id="tab_content2" aria-labelledby="profile-tab">
<table id="datatable-keytable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Date</th>
<th>Ref</th>
<th>Description<i class="fa fa-sort-amount-asc pull-right"></i></th>
<th>Amount</th>
<th><i class="fa fa-caret-down"></i></th>
</tr>
</thead>
<? print_r($withdrawl);
for($a=0;$a<count($withdrawl); $a++){ ?>
<tr>
<td><?=retrieve_date($withdrawl[$a]['enterdate']);?></td>
<td><?=$withdrawl[$a]['reference'];?></td>
<td><?=$withdrawl[$a]['memo'];?></td>
<td><?=number_money($withdrawl[$a]['credit']);?></td>
<td><input type="checkbox" name="withdrawl[]" id="<?=$withdrawl[$a]['transid'];?>" value="<?=$withdrawl[$a]['credit'];?>" onclick="addRecon(this);"/></td>
</tr>
<? } ?>
</table>
document.getElementsByName returns collections of elements,
please refer below link
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName, so whereever you have used getElementsByName for value , it should be document.getElementsByName('startbalance')[0]
Related
Good morning, I want to get all the records in a table and add them to an array and then register them to the database using ajax.
The problem I have is that using .each I get the values of the first row correctly, but when adding another row, the array ends up duplicated.
I share some images so that my problem is better understood
debugging the first row of the table
duplicates
all duplicate table rows
Javascript
function AgregarLista() {
const TD = $('<td></td>');
const TR = $('<tr></tr>');
const TABLE_VENTA = $('#dtVenta');
const PRODUCT_TOTAL = $('#TotalPagar');
let item = 0;
$('#btnAgregarTabla').click(function () {
item++;
let id_cliente = $('#id_cliente').val();
let id_producto = $('#id_producto').select2('val');
let precio_producto = $('#precio').val();
let stock_producto = $('#stock').val();
let cantidad_producto = $('#cantidad').val();
let subtotal_producto = parseInt(precio_producto) * parseInt(cantidad_producto);
let nro_venta = TD.clone().html(item).addClass('nro_sale');
let cliente = TD.clone().html(id_cliente).addClass('td_customer');
let producto = TD.clone().html(id_producto).addClass('td_product');
let precio = TD.clone().html(precio_producto).addClass('td_price');
let stock = TD.clone().html(stock_producto).addClass('td_stock');
let cantidad = TD.clone().html(cantidad_producto).addClass('td_quantity');
let preciototal = TD.clone().html(subtotal_producto).addClass('subtotal');
let newRow = TR.clone().append(nro_venta, cliente, producto, precio, stock, cantidad, preciototal);
let total = subtotal_producto;
$('.subtotal').each(function (index, tr) {
total = total + parseInt($(this).text());
});
TABLE_VENTA.find('tbody').append(newRow);
PRODUCT_TOTAL.find('#total_pagar').val(total);
//*===========================================================
//* here I call the method I use to get the array
//* ==========================================================
loopDetailTable();
});
}
With this code I get the values of the table rows
// * ==============================================
//* With this code I get the values of the table rows
// * ==============================================
function loopDetailTable(params) {
let index = 0;
var obj = new Object();
obj.DetailsList = [];
$('#dtVenta').each(function () {
let item_detalle = new Object();
item_detalle.vNumero = $('.nro_sale').text();
item_detalle.cID = $('.td_customer').text();
item_detalle.pID = $('.td_product').text();
item_detalle.pPrice = $('.td_price').text();
item_detalle.pStock = $('.td_stock').text();
item_detalle.pQuantity = $('.td_quantity').text();
item_detalle.pSubtotal = $('.subtotal').text();
obj.DetailsList[index] = item_detalle;
index++;
console.log(obj);
});
return obj;
}
HTML form
<div class="d-flex">
<div class="col-md-5">
<form role="form">
<div class="card">
<div class="card-body">
<h5>Datos del cliente:</h5>
<div class="form-group d-flex">
<div class="col-md-6 d-flex">
<input type="text" name="dni" id="dni" class="form-control" placeholder="dni cliente">
<input type="button" id="btnBuscarCliente" value="Buscar" class="btn btn-outline-danger">
</div>
<div class="col-md-6">
<input type="hidden" name="id_cliente" id="id_cliente" value="">
<input type="text" name="nombre_cliente" id="nombre_cliente" value="" class="form-control" placeholder="Cliente" disabled>
</div>
</div>
<h5>Datos del producto:</h5>
<div class="form-group d-flex">
<div class="col-md-6 d-flex">
<!-- <input type="text" name="id_producto" id="id_producto" class="form-control" placeholder="codigo producto"> -->
<select name="id_producto" id="id_producto" class="id_producto js-states form-control"></select>
<input type="button" id="btnBuscarProducto" value="Buscar" class="btn btn-outline-danger">
</div>
<div class="col-md-6">
<input type="text" name="nombre_producto" id="nombre_producto" class="form-control" placeholder="Producto" disabled>
</div>
</div>
<div class="form-group row">
<div class="col-md-4">
<input type="text" name="precio" id="precio" class="form-control" placeholder="s/.0.00" disabled>
</div>
<div class="col-md-4">
<input type="number" name="stock" id="stock" class="form-control" placeholder="stock" disabled>
</div>
<div class="col-md-4">
<input type="number" name="cantidad" id="cantidad" value="1" class="form-control" placeholder="cantidad">
</div>
</div>
</div>
<div class="card-footer">
<input type="button" id="btnAgregarTabla" value="Agregar" class="btn btn-primary float-right">
</div>
</div>
</form>
</div>
<div class="col-md-7">
<div class="card">
<div class="card-body">
<div class="d-flex col-md-6 ml-auto">
<label class="mx-3 mt-1">Nro.serie:</label>
<input type="text" name="nro_serie" id="nro_serie" th:value="${serie}" class="form-control">
</div>
<table id="dtVenta" class="table mt-4" style="width: 100%;">
<thead>
<tr>
<th>Nro.Venta</th>
<th>Cliente</th>
<th>Producto</th>
<th>Precio</th>
<th>Stock</th>
<th>Cantidad</th>
<th>SubTotal</th>
<tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div id="TotalPagar" class="card-footer">
<div class="row">
<input type="button" id="btnCancelarVenta" value="Cancelar" class="btn btn-danger">
<input type="button" id="btnGenerarVenta" value="Generar" class="btn btn-success mx-1">
<div class="d-flex ml-auto">
<label for="" class="mx-2 mt-1">Total:</label>
<input type="text" name="total_pagar" id="total_pagar" class="form-control">
</div>
</div>
</div>
</div>
</div>
</div>
Thank you all for your help, greetings.
You get 'duplicates' because of the selector. You select using the class names, which are not unique. For example $('.td_customer').text(); select all customer cells.
Which you don't want. You want only the customer cell of a certain row.
I think you can solve your problem with iterating over the table rows (you iterate over the tables with id dtVenta, that's only one table).
So try something like:
$('#dtVenta tr').each(function () {
// $(this) is the 'current' row of the table
let item_detalle = new Object();
item_detalle.vNumero = $(this).find('.nro_sale').text(); // find all child .nro_sale cells and get it's text
item_detalle.cID = $(this).find('.td_customer').text();
item_detalle.pID = $(this).find('.td_product').text();
item_detalle.pPrice = $(this).find('.td_price').text();
item_detalle.pStock = $(this).find('.td_stock').text();
item_detalle.pQuantity = $(this).find('.td_quantity').text();
item_detalle.pSubtotal = $(this).find('.subtotal').text();
obj.DetailsList[index] = item_detalle;
index++;
console.log(obj);
});
I'm trying to figure out how to store the data from a dynamic table to the database.
Here's the idea: I'm developing a system to control the drivers journey. It basically will store the day work of the driver, spliting it on differente intervals, such as: Driving time, meal time, waiting time, etc (all of them in HH:MM). They will be adding in different tables, as the following picture shows.
Journey Control
The input data (hour), for each table, can be different. It will depend on the driver's day journey. I need to catch and store those hours on a database.
My best idea is to get all those hours after the user ends the input, but how do I store that if I don't have the field's name?
Additional information: I'm using Java, SpringBoot and Thymeleaf to develop it.
JourneyControl.RegisterHourJourney = (function() {
var counterDriving = 0;
var counterInterval = 0;
var counterMeal = 0;
var counterWaiting = 0;
var counterRest = 0;
function RegisterJourneyHour() {
this.novaDrivingBtn = $('.js-add-new-direcao');
this.novoIntervalBtn = $('.js-add-new-intervalo');
this.novaMealBtn = $('.js-add-new-refeicao');
this.novaWaitingBtn = $('.js-add-new-espera');
this.novoRestBtn = $('.js-add-new-pernoite');
this.deleteDrivingBtn = $('#direcaot');
this.deleteIntervalBtn = $('#intervalot');
this.deleteMealBtn = $('#refeicaot');
this.deleteWaitingBtn = $('#esperat');
this.deleteRestBtn = $('#pernoitet');
}
RegisterHourJourney.prototype.start = function() {
this.novaDrivingBtn.on('click', onAdicionarHourDriving.bind());
this.novoIntervalBtn.on('click', onAdicionarHourInterval.bind());
this.novaMealBtn.on('click', onAdicionarHourMeal.bind());
this.novaWaitingBtn.on('click', onAdicionarHourWaiting.bind());
this.novoRestBtn.on('click', onAdicionarHourRest.bind());
this.deleteDrivingBtn.on('click', '.js-delete-btn',
onDeleteHourDriving.bind());
this.deleteIntervalBtn.on('click', '.js-delete-btn',
onDeleteHourInterval.bind());
this.deleteMealBtn.on('click', '.js-delete-btn',
onDeleteHourMeal.bind());
this.deleteWaitingBtn.on('click', '.js-delete-btn',
onDeleteHourWaiting.bind());
this.deleteRestBtn.on('click', '.js-delete-btn',
onDeleteHourRest.bind());
}
function onAdicionarHourDriving() {
/*var newRow = $("<tr id=\" " + + counterDriving + " \">");*/
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioDirecao').val();
var inputFim = $('#fimDirecao').val();
var direcao = $('#direcao').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class=" btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#direcaot").append(newRow);
counterDriving++;
$('#inicioDirecao').val('');
$('#fimDirecao').val('');
}
}
function onAdicionarHourInterval() {
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioIntervalo').val();
var inputFim = $('#fimIntervalo').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class="btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#intervalot").append(newRow);
counterInterval++;
$('#inicioIntervalo').val('');
$('#fimIntervalo').val('');
}
}
function onAdicionarHourMeal() {
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioRefeicao').val();
var inputFim = $('#fimRefeicao').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class="btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#refeicaot").append(newRow);
counterMeal++;
$('#inicioRefeicao').val('');
$('#fimRefeicao').val('');
}
}
function onAdicionarHourWaiting() {
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioEspera').val();
var inputFim = $('#fimEspera').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class="btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#esperat").append(newRow);
counterWaiting++;
$('#inicioEspera').val('');
$('#fimEspera').val('');
}
}
function onAdicionarHourRest() {
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioPernoite').val();
var inputFim = $('#fimPernoite').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class="btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#pernoitet").append(newRow);
counterRest++;
$('#inicioPernoite').val('');
$('#fimPernoite').val('');
}
}
function onDeleteHourDriving() {
var item = document.activeElement;
item.closest("tr").remove();
counterDriving -= 1;
}
function onDeleteHourInterval() {
var item = document.activeElement;
item.closest("tr").remove();
counterInterval -= 1;
}
function onDeleteHourMeal() {
var item = document.activeElement;
item.closest("tr").remove();
counterMeal -= 1;
}
function onDeleteHourWaiting() {
var item = document.activeElement;
item.closest("tr").remove();
counterWaiting -= 1;
}
function onDeleteHourRest() {
var item = document.activeElement;
item.closest("tr").remove();
counterRest -= 1;
}
return RegisterHourJourney;
}());
$(function() {
var RegisterHourJourney = new JourneyControl.RegisterHourJourney();
RegisterHourJourney.start();
});
<body>
<section layout:fragment="conteudo">
<div class="page-header">
<div class="container-fluid">
<div class="row">
<div class="col-xs-10">
<h1>Journey Control</h1>
<!-- <h1 th:if="${empresa.nova}">Cadastrar jornada</h1> -->
<!-- <h1 th:unless="${empresa.nova}" th:text="|Editar empresa - ${empresa.razaoSocial}|">Editar jornada</h1> -->
</div>
<div class="col-xs-2">
<div class="aw-page-header-controls">
<!-- <a class="btn btn-default" th:href="#{/empresas}"> -->
<a class="btn btn-default">
<i class="glyphicon glyphicon-plus-sign"></i>
<span class="hidden-xs hidden-sm">Search Journey</span>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<!-- <form method="POST" th:object="${jornada}" class="form-vertical js-form-loading"
th:action="${empresa.nova} ? #{/empresas/nova} : #{/empresas/{codigo}(codigo=${empresa.codigo})}"> -->
<form class="form-vertical js-form-loading">
<!-- <cj:message/> -->
<!-- <input type="hidden" th:field="*{codigo}" /> -->
<div class="row">
<div class="col-sm-2 form-group field-required">
<label for="data" class="control-label">Date</label>
<input id="data" type="text" class="form-control js-date" />
</div>
<div class="col-sm-5 form-group field-required">
<label for="motorista" class="control-label">Driver</label>
<input id="motorista" type="text" class="form-control" autofocus="autofocus" />
</div>
<div class="col-sm-1 form-group">
<label class="control-label">Day off</label>
<div>
<input type="checkbox" class="js-status" data-size="small" data-off-color="danger"
data-on-text="Yes" data-off-text="No" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Driving Time</legend>
<div class="form-group row">
<!-- <label for="inicioDirecao" class="col-sm-1 col-form-label">Start</label> -->
<label for="inicioDirecao" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioDirecao" type="text" class="form-control js-hora">
<input type="hidden" value="DIRECAO"/>
</div>
<label for="EndDirecao" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndDirecao" type="text" class="form-control js-hora">
<input type="hidden" value="DIRECAO"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-direcao">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="direcaot">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Driving Interval</legend>
<div class="form-group row">
<label for="inicioIntervalo" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioIntervalo" type="text" class="form-control js-hora">
<input type="hidden" value="INTERVALO"/>
</div>
<label for="EndIntervalo" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndIntervalo" type="text" class="form-control js-hora">
<input type="hidden" value="INTERVALO"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-intervalo">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="intervalot">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Meal</legend>
<div class="form-group row">
<label for="inicioRefeicao" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioRefeicao" type="text" class="form-control js-hora">
<input type="hidden" value="REFEICAO"/>
</div>
<label for="EndRefeicao" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndRefeicao" type="text" class="form-control js-hora">
<input type="hidden" value="REFEICAO"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-refeicao">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="refeicaot">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Waiting Time</legend>
<div class="form-group row">
<label for="inicioEspera" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioEspera" type="text" class="form-control js-hora">
<input type="hidden" value="ESPERA"/>
</div>
<label for="EndEspera" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndEspera" type="text" class="form-control js-hora">
<input type="hidden" value="ESPERA"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-espera">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="esperat">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Rest</legend>
<div class="form-group row">
<label for="inicioPernoite" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioPernoite" type="text" class="form-control js-hora">
<input type="hidden" value="PERNOITE"/>
</div>
<label for="EndPernoite" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndPernoite" type="text" class="form-control js-hora">
<input type="hidden" value="PERNOITE"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-pernoite">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="pernoitet">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Salvar</button>
</div>
</form>
</div>
</section>
<th:block layout:fragment="javascript-extra">
<script th:src="#{/javascripts/jornada.mascara-horas.js}"></script>
<script th:src="#{/javascripts/vendors/bootstrap-switch.min.js}"></script>
<script th:src="#{/javascripts/cadastro_jornada.js}"></script>
<script>
$('.js-status').bootstrapSwitch();
</script>
</th:block>
</body>
An example for meals:
When you add a new row, give it a name in the way of name="meal[" + nextMeal + "]", this nomenclature will map your new meal to a list of meals in the controller on form submission.
To know what's the proper value for nextMeal, do something like this:
var nextMeal = 0;
while($("tr[name='nextMeal[" + nextMeal + "]']").length){
nextMeal++;
}
I've a razor form that I want to clone on button click such that I get unique ID for all the form fields. I'm able to do this if do not put any of the input elements in div or table. But when I do that, I do not get unique IDs. I've tried various solutions but nothing seems to work.
This is my razor code of form to be cloned
<div id="bookingForm" style="display:none; color:#fff;" class="container">
#{
int index = 0;
int hall = 0, slot = 0, requirement = 0;
<div style="font-family: 'Roboto', sans-serif;margin-bottom:30px;" class="row">
<div class="col-md-4 col-sm-4 col-4">
<label><h2>Starting Date</h2></label><br>
</div>
<div class="col-md-7 col-sm-7 col-7">
<input type="date" name="detailsObjList[#index].date" id="date" required onchange="datechosen();" style="width: 100%;" class="form-control start" />
</div>
#foreach (var item in ViewBag.HallDetail)
{
slot = 0;
<hr />
<span id="invalidDate" style="color:indianred;"></span>
<br />
<div style="font-family: 'Montserrat', sans-serif;" class="col-4">
<input type="hidden" name="detailsObjList[#index].hallsArray[#hall].hallID" value="#(item.hallID)" id="hiddenhall#(hall)_" />
<input type="hidden" name="detailsObjList[#index].hallsArray[#hall].hallName" value="#item.hallName" id="hiddenhallname#(hall)_" />
<label>#item.hallName :</label>
</div>
<div style="align-content: center;" class="col-8">
<table class="table table-responsive table-striped">
<tbody>
<tr>
<!--SLOTS-->
#foreach (var slotItem in item.slotsArray)
{
<th>
<input type="hidden" name="detailsObjList[#index].hallsArray[#hall].slotsArray[#slot].slotID" value="#(slotItem.slotID)" id="hiddenslot#(slot + 1)_#(hall + 1)_" />
<label class="custom-control custom-checkbox" id="lblSlot#(slot+1)_#(hall + 1)_" onmouseover="seeDetails(#(slot+1),#(hall+1))" style="color:#fff;">
<input type="checkbox" class="custom-control-input" data-toggle="tooltip" name="detailsObjList[#index].hallsArray[#hall].slotsArray[#slot].isSelected" id="slotcheck#(slot + 1)_#(hall + 1)_" onchange="slotcheckchange(#(slot + 1), #(hall + 1));" />
<span class="custom-control-indicator"></span><span class="custom-control-description">#slotItem.slot</span>
</label>
<span id="span#(slot+1)_#(hall + 1)_" style="color:indianred;"></span>
</th>
slot = slot + 1;
}
</tr>
</tbody>
</table>
</div>
hall = hall + 1;
}
</div>
hall = 0;
slot = 0;
}
</div>
I'm cloning this form below
#using (Html.BeginForm("Testing", "BookUtility", FormMethod.Post))
{
<span id="writeroot"></span>
<button class="btn btn-success"><i class="fa fa-check-circle" aria-hidden="true"></i> Submit</button>
}
<button id="btnAddMore" class="btn btn-danger" onclick="addMore(#index, #hall, #slot);"><i class="fa fa-plus-circle" aria-hidden="true"></i> Add more</button>
JavaScript Code:
var click = 0;
var addMore = function (index, hall, slot) {
click = click + 1;
var newFields = document.getElementById('bookingForm').cloneNode(true);
newFields.id = '';
newFields.style.display = '';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var newId = newField[i].id
if (newId)
newField[i].id = newId + click;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields, insertHere);
}
This is my whole code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Pre-Enrollment</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/customcss.css">
</head>
<nav>
<ul class="nav nav-tabs">
<li role="presentatoion" class="active">Pre-Enrollment</li>
<li role="presentation">Students</li>
<li role="presentation">Subjects</li>
</ul>
</nav>
<br>
<body>
<div class="container">
<div class="row"> <!--RED-->
<div class="col-md-3" >
<form id="idNumber" action="FromEnrollment.php" method="POST">
<div class="input-group">
<!-- <input type="text" class="form-control" placeholder="ID NUMBER"> -->
<span class="input-group-btn">
<!--<form action="newPhp.php" method="POST">-->
<input type="text" placeholder="ID NUMBER" class="form-control" name="input">
<input type="submit" value="Enter" name"Enter" class="btn btn-default">
<!--</form>-->
<button class="btn btn-default" type="button" onclick="resetIdNumber()" value="reset">Reset</button>
</span>
</div>
</form>
</div>
<div class="col-md-4 col-md-offset-3">
<select style="width: 120px;">
<option value="All">Overall Term</option>
<option value="First">First Term</option>
<option value="Second">Second Term</option>
<option value="Short">Short Term</option>
</select>
</div>
<div class="col-md-2">
<button class="btn btn-primary" type="button">Apply</button>
<button class="btn btn-default" type="button" onclick="myFunction()" value="reset">Reset</button>
</div>
</div>
<br>
<div class="row" >
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if( isset($_POST['input']) ){
include 'dbcon.php';
$Idnumber = ($_POST['input']);
$stmt = $pdo->query("SELECT * FROM students WHERE id_number = '$Idnumber'");
$currentTerm = $pdo->query("SELECT * FROM pre_enroll WHERE id_number = '$Idnumber'");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result2 = $currentTerm->fetchAll(PDO::FETCH_ASSOC);
// $last_name = print_r($result[0]['last_name']);
// $first_name = print_r($result[0]['first_name']);
// $course = print_r($result[0]['course']);
echo "
<div class='col-md-2'>
<p>Name: ";
print_r($result[0]['last_name']);
echo " ";
print_r($result[0]['first_name']);
echo"</p>
</div>";
echo "
<div class='col-md-4'>
<p>Course and Year: ";
print_r($result[0]['course']);
echo"-";
print_r($result[0]['year']);
echo"</p>
</div>";
echo "
<div class='col-md-4'>
<p>Current term: ";
print_r($result2[0]['term']);
echo"</p>
</div>";
// <div class='col-md-4'>
// <p>Current Term: </p>
// </div>;
}
}else{
echo "
<div class='col-md-2'>
<p>Name: </p>
</div>
<div class='col-md-4'>
<p>Course and Year: </p>
</div>
<div class='col-md-4'>
<p>Current Term: </p>
</div>";
}
?>
</div>
<br>
<div class="row">
<div class="col-md-6">
<form id="Subjects" action="#">
<div class="input-group">
<input type="text" id="myInput" onkeyup="filterData()" class="form-control" placeholder="Search for...">
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="resetSubjects()" value="reset">Reset</button>
</span>
</div>
</form>
</div>
<div class="col-md-2">
<p>Total Units: <b> </b></p>
</div>
</div>
<br>
<?php
include 'dbcon.php';
$stmt = $pdo->query("SELECT subjects.coursenumber as 'Course No.', subjects.destitle as 'Descriptive Title', enr_stat.term as 'Term', subjects.units as 'Units' FROM subjects INNER JOIN enr_stat ON subjects.coursenumber = enr_stat.coursenumber");
?>
<div class="row">
<div class="col-md-6 col" id="table-wrapper">
<div id="table-scroll">
<table class="table" id="myTable">
<tr>
<th>Course No.</th>
<th>Descriptive Title</th>
<th>Term</th>
<th>Unit</th>
<th></th>
</tr>
<?php
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
// echo "<form action=''>";
echo "<tr>";
echo "<td>".$row['Course No.']."</td>";
echo "<td>".$row['Descriptive Title']."</td>";
echo "<td>".$row['Term']."</td>";
echo "<td>".$row['Units']."</td>";
echo "<input type='hidden' name='CourseNo' value='".$row['Course No.']."'/>";
echo "<input type='hidden' name='descrp' value='".$row['Descriptive Title']."'/>";
echo "<input type='hidden' name='term' value='".$row['Term']."'/>";
echo "<input type='hidden' name='units' value='".$row['Units']."'/>";
echo "
<td>
<button class='btn btn-default btn-sm' onclick='addDataToLocalStorage(this)'>
<span class='glyphicon glyphicon-plus' aria-hidden='true'></span>
</button>
</td>
";
echo "</tr>";
// echo "</form>";
}
?>
</table>
</div>
</div>
<div class="col-md-6 col" id="table-wrapper">
<div id="table-scroll">
<table class="table" id="copy">
<tr>
<th>Course No.</th>
<th>Descriptive Title</th>
<th>Term</th>
<th>Unit</th>
<th></th>
</tr>
</table>
</div>
</div>
</div>
<div class="col-md-offset-11">
<button class="btn btn-primary" type="button">Apply</button>
<br>
</div>
<script>
function resetIdNumber(){
document.getElementById("idNumber").reset();
}
function resetSubjects(){
document.getElementById("Subjects").reset();
}
function filterData() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
function addDataToLocalStorage(r){
var courseNo = r.parentNode.parentNode.childNodes[0].innerText;
var descriptive = r.parentNode.parentNode.childNodes[1].innerText;
var term = r.parentNode.parentNode.childNodes[2].innerText;
var unit = r.parentNode.parentNode.childNodes[3].innerText;
var t = "<button onclick=clearData(this);deleteRow(this); class='btn btn-default btn-sm'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>";
// alert(courseNo + " " + descriptive + " " + unit);
var list = {
courseNumber: courseNo,
descriptiveTitle: descriptive,
term: term,
units: unit,
};
var jsonObject = JSON.stringify(list);
localStorage.setItem("list" + localStorage.length,jsonObject);
var thatTable = document.getElementById("copy");
var newRow = thatTable.insertRow(-1); //at the last position of the table
var newCell1 = newRow.insertCell(0);
newCell1.innerHTML = courseNo;
var newCell2 = newRow.insertCell(-1);
newCell2.innerHTML = descriptive;
var newCell3 = newRow.insertCell(-1);
newCell3.innerHTML = term;
var newCell4 = newRow.insertCell(-1);
newCell4.innerHTML = unit;
var newCell5 = newRow.insertCell(-1);
newCell5.innerHTML = t;
}
function clearData(r) {
var data = r.parentNode.parentNode.rowIndex;
var data_key = data - 1;
localStorage.removeItem(localStorage.key(data_key));
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("copy").deleteRow(i);
}
// function refresh(){
// if (localStorage.getItem("list0") != null) { ///if there is "student1" exist in localStorage
// for(i = 0; i <= localStorage.length; i++){
// var stores = localStorage.getItem("list" + i);
// var jsonString = JSON.parse(stores); //convert text to javascript object
// var thatTable = document.getElementById("copy");
// var newRow = thatTable.insertRow(-1); //at the last position of the table
// var newCell1 = newRow.insertCell(0);
// newCell1.innerHTML = courseNo;
// var newCell2 = newRow.insertCell(-1);
// newCell2.innerHTML = descriptive;
// var newCell3 = newRow.insertCell(-1);
// newCell3.innerHTML = term;
// var newCell4 = newRow.insertCell(-1);
// newCell4.innerHTML = unit;
// var newCell5 = newRow.insertCell(-1);
// newCell5.innerHTML = t;
// }
// }
//}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
How can I increment my <p>Total Units:<b> </b></p> whenever I clicked add button in my table. My table fetched some data in my database and when I clicked add, The data will copy in the next html table. I want every time I clicked the add button, my <p> tag will increment by how many units the subject is.
I tried using the stepUp() method in js but I dont know how to get the value of the units row in my html table. Is there any way to do it with my current codes?
You can just use a span with special ID
<p>Total Units:<b><span id="countRow"></span></b></p>
Then count your rows, and just
document.getElementById("countRow").innerHTML = count
Set any class name to the column units like this
<td class="unit" >2</td>
Each time of button click after run the each function like this
var total=0;
$('.unit').each(function(){ total+=parseInt($(this).text()); });
And set any class name to p tag
$('.p_tag_class').html('Total Units:' +total+'<b> </b>');
Update 1:
$(document).on('click','[type="button"]',function(){
$('table tbody').last('tr').append('<tr><td >2</td><td class="unit">8</td></tr>');
total=0;
$('.unit').each(function(){ total+=parseInt($(this).text()); });
$('.total').text(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1px">
<thead>
<tr>
<th>colum1</th>
<th >colum2</th>
</tr>
</thead>
<tbody>
<tr>
<td >1</td>
<td class="unit">6</td>
</tr>
<tr>
<td >2</td>
<td class="unit">8</td>
</tr>
</tbody>
</table>
<input type="button" value="new row" />
<p class="total" ></p>
I have a dynamic table, which contains some data.In my table there is a option called Edit,by clicking the edit option a SideNav is opening.I want to fetch that particular row from the table and want to place those information into my sideNav.
My HTML and JS file is below.
/index.html
<table class="table-bordered mytable">
<thead class="table-head">
<tr>
<th>Name</th>
<th>Email</th>
<th>Status</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody class="table-body mytabBody">
</tbody>
</table>
<div id="mySidenav" class="sidenav">
<div class="border">
×
</div>
<div class="border">
<form class="navbar-form" id="editUserInfo">
<div class="form-group">
<input type="text" class="form-control" id="user_name" placeholder="User name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email_id" placeholder="Enter email">
</div>
<div class="form-group">
<input type="text" class="form-control" id="address" placeholder="Enter Address">
</div>
<button type="submit" value="signin" class="btn btn-custom" onclick="editUser()">Edit</button>
</form>
</div>
</div>
/table.js
$(function(){
$.get("/api/dashboard/v1", function (response) {
// console.log(response);
var myhtmlsec= "";
for(var i=0; i<response.data.length; i++) {
myhtmlsec += "<tr>";
myhtmlsec +="<td>"+response.data[i].user_name+"</td>";
myhtmlsec +="<td>"+response.data[i].email+"</td>";
myhtmlsec +="<td></td>";
myhtmlsec +="<td>"+response.data[i].address+"</td>";
myhtmlsec +="<td>\
<a href='#' onclick='myEdit(this);return false;' class='table-edit img-size'>\
<img src='image/Edit.png'>\
</img>\
</a>\
<a href='#' onclick='myDelete();return false;' class='table-delete img-size'>\
<img src='image/Delete.png'>\
</img>\
</a>\
</td>";
myhtmlsec +="</tr>"
}
$('.table-body').append(myhtmlsec);
});
});
function myEdit(a) {
document.getElementById("mySidenav").style.width = "250px";
/*console.log(a);
var b = $(a).closest('tr');
console.log(b);
*/
};
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
};
function editUser() {
var par = $(this).parent().parent();
var tdName = par.children("td:nth-child(1)");
var tdEmail = par.children("td:nth-child(2)");
var tdAddress = par.children("td:nth-child(3)");
//want to edit/update userinformation through this "api/updateUser/v1:id" using put method
}
function myDelete() {
alert();
};
using jquery
function myEdit(elem)
{
$('#user_name').val($(elem).parent().parent().find('td:nth-child(1)').html());
...
/* fill other fields */
}
Here is perfect and clean solution:
$('tbody tr').click(
function(){
var name = $(this).find("td:nth-child(1)").html();
var email = $(this).find("td:nth-child(2)").html();
var addr = $(this).find("td:nth-child(3)").html();
$('#user_name').val(name);
$('#email_id').val(email);
$('#address').val(addr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<table class="table-bordered mytable">
<thead class="table-head">
<tr>
<th>Name</th>
<th>Email</th>
<th>Status</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody class="table-body mytabBody">
<tr>
<td>Pravin</td>
<td>pravin#gmail.com</td>
<td>True</td>
<td>Nagpur</td>
<td>Click</td>
</tr>
</tbody>
</table>
<div id="mySidenav" class="sidenav">
<div class="border">
×
</div>
<div class="border">
<form class="navbar-form" id="editUserInfo">
<div class="form-group">
<input type="text" class="form-control" id="user_name" placeholder="User name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email_id" placeholder="Enter email">
</div>
<div class="form-group">
<input type="text" class="form-control" id="address" placeholder="Enter Address">
</div>
<button type="submit" value="signin" class="btn btn-custom" onclick="editUser()">Edit</button>
</form>
</div>
</div>