Clone form with input elements in div - javascript

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);
}

Related

How to send data to a table with jQuery?

I would like someone to answer my question about how I can make the data typed in the Agenda fields be added to the table, with jQuery. Currently the table adds rows and also deletes them, but does not add the data entered in the form fields. Finally, I can't make the "save" button be placed below the table, or above it, static.
HTML - atv1-1:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<title>João Augusto - Agenda jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="estilos.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<div class="p-5 text-black text-center bg-roxo">
<h1 id="titulo">João Augusto</h1>
</div>
<div class="container mt-5">
<div class="container">
<h5>Agenda</h5>
<form id="formulario">
<div class="row py-2">
<div class="col-1">
<label for="nome">Nome:</label>
</div>
<div class="col-5 ">
<input type="text" class="form-control" placeholder="Escrava o primeiro nome" name="nome">
</div>
</div>
<div class="row py-2">
<div class="col-1">
<label for="email">Email:</label>
</div>
<div class="col-5">
<input type="text" class="form-control" placeholder="email" name="email">
</div>
<div class="col-1">
<label for="cel">Celular:</label>
</div>
<div class="col-5">
<input type="text" class="form-control" placeholder="(XX)XXXX-XXXX" name="cel">
</div>
</div>
<div class="row py-2">
<div class="col-1">
<label for="insta">Instagram:</label>
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Instagram" name="insta">
</div>
<div class="col-1">
<label for="face">Facebook:</label>
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Facebook" name="face">
</div>
</div>
</form>
</div>
<!-- Tabela que conterá os dados-->
<div class="container mt-3">
<table class="table table-striped" id="myTable">
<tbody>
<tr>
<th>Nome</th>
<th>Email</th>
<th>Instagram</th>
<th>Celular</th>
<th>Facebook</th>
<th>Excluir</th>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td>
<button type="button" onclick="remove(this)" class="btn btn-danger btn-xs">Excluir</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<button class='btn btn-danger excluir' onclick="AddTableRow()" type="button">Salvar</button>
</tr>
</tfoot>
</table>
</div>
</div>
<div class="mt-5 p-4 bg-dark text-white text-center">
</div>
<script src="functions.js"></script>
</body>
</html>
jQuery (JS) - functions.js :
(function($) {
AddTableRow = function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td> </td>';
cols += '<td> </td>';
cols += '<td> </td>';
cols += '<td> </td>';
cols += '<td> </td>';
cols += '<td>';
cols += '<button type="button" onclick="remove(this)" class="btn btn-danger btn-xs">Excluir</button>';
cols += '</td>';
newRow.append(cols);
$("#myTable").append(newRow);
return false;
};
})(jQuery);
(function($) {
remove = function(item) {
var tr = $(item).closest('tr');
tr.fadeOut(400, function() {
tr.remove();
});
return false;
}
})(jQuery);
This is my working solution:
View this on codepen.io
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="functions.js"></script>
FORM and Table, HTML: (Just replace this instead your form and your table
)
<form id="formulario">
<div class="row align-items-center py-2">
<div class="col-1">
<label for="nome">Nome:</label>
</div>
<div class="col-5 ">
<input type="text" class="form-control" placeholder="Escrava o primeiro nome" name="nome" value="JOÃO AUGUSTO">
</div>
<div class="col-1">
<label for="email">Select:</label>
</div>
<div class="col-5">
<select class="form-select" name="select">
<option value="">Not choosed</option>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
<option value="Option4">Option4</option>
</select>
</div>
</div>
<div class="row align-items-center py-2">
<div class="col-1">
<label for="email">Email:</label>
</div>
<div class="col-5">
<input type="text" class="form-control" placeholder="email" name="email">
</div>
<div class="col-1">
<label for="cel">Celular:</label>
</div>
<div class="col-5">
<input type="text" class="form-control" placeholder="(XX)XXXX-XXXX" name="celular">
</div>
</div>
<div class="row align-items-center py-2">
<div class="col-1">
<label for="insta">Instagram:</label>
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Instagram" name="instagram">
</div>
<div class="col-1">
<label for="face">Facebook:</label>
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Facebook" name="facebook">
</div>
</div>
</form>
<div class="col-auto p-0 mt-3">
<button class="btn btn-success" onclick="Functions.addToTable('formulario','myTable')" type="button">Salvar</button>
</div>
</div>
<div class="container mt-3">
<table class="table table-striped text-center table-bordered my-3" id="myTable">
<tbody>
<!-- IF EMPTY ROWS :
<tr id="emptyTr"><td><i>empty</i></td></tr>
-->
<!-- IF CONST ROWS : -->
<tr id="tr_1">
<td><i>name</i></td>
<td><i>select</i></td>
<td><i>email</i></td>
<td><i>celular</i></td>
<td><i>instagram</i></td>
<td><i>facebook</i></td>
<td>
<button onclick="Functions.removeFromTable('formulario','myTable',1)" type="button" class="btn btn-sm btn-danger btn-xs">
Excluir
</button>
</td>
</tr>
<!---end Const Rows---->
</tbody>
</table>
functions.js: (just replace all this instead your functions.js)
//develope by: https://stackoverflow.com/users/3114914/
class Functions {
static trNumbers(tableId){
var table = $('#'+tableId);
var issetEmptyTr = table.find('tbody tr#emptyTr').length;
if(issetEmptyTr==1)
return 1;
else
return parseInt(table.find('tbody tr:last').attr('id').replace(/\D/g,''))+1;
}
static formData(formId){
var map = new Map();
var formInputLength = parseInt($('#'+formId+' input').length);
var formSelectLength = parseInt($('#'+formId+' select').length);
var formLength = formInputLength + formSelectLength;
for(let i=0; i < formLength; i++)
{
var inpName = $('#'+formId+' input, #'+formId+' select').eq(i).attr('name')
var inpVal = $('#'+formId+' input, #'+formId+' select').eq(i).val()
var inpMap = map.set(''+inpName+'',''+inpVal+'');
}
return inpMap;
}
constructor(formId,tableId){
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var formData = Functions.formData(formId)
var table = $('#'+tableId);
table.prepend('<thead class="bg-light"><tr></tr></thead>')
var th = '';
var formDataKeys = formData.keys();
for(let i=0; i<formData.size; i++){th+='<th>'+capitalizeFirstLetter(formDataKeys.next().value)+'</th>'}
th += '<th>Excluir</th>';
table.find('thead tr').html(th);
table.find('tbody').find('#emptyTr td').attr('colspan',formData.size+1);
}
static addToTable(formId,tableId){
var formData = Functions.formData(formId);
var table = $('#'+tableId);
var formDataKeys = formData.values();
var td = '';
var number = Functions.trNumbers(tableId);
for(let i=0; i<formData.size; i++){td+='<td>'+formDataKeys.next().value+'</td>'}
td += '<td><button onclick=Functions.removeFromTable("'+formId+'","'+tableId+'",'+number+') type="button" class="btn btn-sm btn-danger btn-xs">Excluir</button></td>';
table.find('tbody').find('#emptyTr').remove()
table.find('tbody').append('<tr id="tr_'+number+'">'+td+'</tr>')
number++;
//SEND and RECEIVE DATA here. for add your row data.
//your MAP => formData. your MAP keys => formData.keys() and values => formData.values()
}
static removeFromTable(formId,tableId,rowId){
var formData = Functions.formData(formId)
var table = $('#'+tableId);
var td = '<td colspan='+formData.size+1+'><i>empty</i></td>';
$('#tr_'+rowId).remove()
var trLength = $('tbody tr').length;
if(trLength==0)
{
table.find('tbody').html('<tr id="emptyTr">'+td+'</tr>')
}
//for DELETE your row data, SEND and RECEIVE DATA here.
}
}
new Functions("formulario","myTable"); // "formulario" is your form id and "myTable" is your table id.
Replace the two above and leave the rest of your code unchanged.
It automatically puts the name of the input/select name="" in the table header.
And puts input/select value="" in own column.
It considers the number of your input/select correctly.
Please Look at the comment in the codes.
Your form id is "formulario" , your table id is "myTable".
and i did'nt change it.
For change this ids:
go to last line of function.js and change:
new Functions("your_new_form_id","your_new_table_id");
go to your Salvar button and Excluir button onclick=""
and change ids:
Functions.addToTable('your_new_form_id','your_new_table_id');
Functions.removeFromTable('your_new_form_id','your_new_table_id','your_table_row_number');
Good luck!
my english is not good. sorry :)

When to use $ .each get duplicate values ​from the rows of a table

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);
});

How to store the data from a dynamic table to database

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++;
}

checking account reconcile formula with positive and negative numbers

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]

Sum the variable array values which depends on event

good day to all of you. I am having trouble on how can I implement the logic of summing up the value of my indexed variable which changes on an event.
When the user has selected a value in select (the quantity is declared and has a default value of 1) the update() will trigger and will compute the total_amount.
The problem I encountered is when I clicked addNewField() and new input has been created an input a new value to the added field, the total_amount is computing only that specific index field and not summing up all the indexed fields.
JS file
vm.update = function(index) {
vm.amount[index] = vm.quantity[index] * vm.selectedItem[index].price;
for(var i=0; i <= index; i++){
var sum = 0;
sum += parseInt(vm.amount[i]);
}
vm.total_amount = sum;
}
vm.addNewField = function(){
if(checkValue() == true){
var index = vm.fields.length;
vm.fields.push({'id': index });
vm.quantity[index] = 1;
}
}
HTML file
<div class="row" ng-repeat="field in vm.fields track by $index">
<div class="form-group col-sm-8">
<label>Item Name</label>
<select ng-model="vm.selectedItem[$index]" ng-options="item as item.item_name for item in vm.items" ng-change="vm.update($index)" class="form-control">
</select>
</div>
<div class="col-sm-3">
<div class="form-group">
<label>Quantity</label>
<input type="number" class="form-control" ng-change="vm.update($index)" ng-model="vm.quantity[$index]" placeholder="123">
</div>
</div>
<div class="col-sm-1">
<div class="form-group">
<a ng-show="$index != '0'" href="" ng-click="vm.removeField($index)" class="button"><i class="fa fa-lg fa-trash"></i>
</a>
</div>
</div>
</div>
<div class="card-footer">
<button type="button" ng-click="vm.addNewField()" class="btn btn-sm btn-primary "><i class="fa fa-plus-circle"></i> Add Field</button>
</div>
<div class="row">
<div class="col-sm-6">
<label><strong>Total Amount:</strong></label>
</div>
<div class="col-sm-6" >
<label><strong>{{ vm.total_amount }}</strong></label>
</div>
</div>
var sum = 0;
for(var i=0; i <= index; i++){
sum += parseInt(vm.amount[i]);
}
Sum should be outside loop

Categories

Resources