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 :)
Related
My problem is that I am trying to make every line added by the user of the program be removed, but only line by line, as I will show below. Currently my program is removing all the rows from the table and that is not the objective, yes, that added many - as many as the user wants -, that he has the possibility of removing a row, if he wants.
var tituloPag = document.getElementById("titulo");
tituloPag.addEventListener("click", function() {
tituloPag.textContent = "Bem vindo a sua agenda";
});
var botaoAdd = document.getElementById("adicionar-contato");
botaoAdd.addEventListener("click", addContato);
function addContato(event) {
event.preventDefault();
var contatoTr = document.createElement("tr");
var formContato = document.getElementById("formulario");
var nomeTd = document.createElement("td");
var emailTd = document.createElement("td");
var celularTd = document.createElement("td");
var instaTd = document.createElement("td");
var faceTd = document.createElement("td");
var excluirTd = document.createElement("td");
nomeTd.textContent = formContato.nome.value;
emailTd.textContent = formContato.email.value;
celularTd.textContent = formContato.cel.value;
instaTd.textContent = formContato.insta.value;
faceTd.textContent = formContato.face.value;
excluirTd.innerHTML = "<button class='btn btn-danger excluir'><i class='fa fa-trash-o' >Excluir</i></button>";
contatoTr.appendChild(nomeTd);
contatoTr.appendChild(emailTd);
contatoTr.appendChild(celularTd);
contatoTr.appendChild(instaTd);
contatoTr.appendChild(faceTd);
contatoTr.appendChild(excluirTd);
var agendaTabela = document.getElementById("corpoAgenda");
agendaTabela.appendChild(contatoTr);
}
<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>
<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>
<div class="salvarexcluir">
<button type="button" class="btn btn-info" id="adicionar-contato">Salvar</button>
<button class='btn btn-danger exluir'><i class='fa fa-trash-o'>Excluir</i></button>
</div>
</form>
</div>
<div class="container mt-3">
<table class="table table-striped" id="myTable">
<thead>
<tr>
<th>Nome</th>
<th>Email</th>
<th>Celular</th>
<th>Instagram</th>
<th>Facebook</th>
<th>Excluir</th>
</tr>
<tr>
</thead>
<tbody id="corpoAgenda">
</tbody>
</table>
</div>
</div>
<div class="mt-5 p-4 bg-dark text-white text-center">
</div>
Instead of trying to add your "delete" action globally for the table, assign the click event separately to each individual row's delete button, so it can get a reference to the row you actually want to delete.
The significant change here was to add these lines to your row creation function:
// attach the "delete" action to this button for this row
excluirTd.querySelector('button').addEventListener("click", () => {
deletar(contatoTr)
})
Previously your code attempted to pass a reference to the button to your deletar function, and then traverse to its parentNode to find the row and its rowIndex. This didn't work because the button's parent node was actually the <td>, not the <tr> you wanted. You could fix that by using parentNode.parentNode, but that would be pretty fragile; instead I changed it to simply pass the row itself, since you conveniently already ha a reference to it in contatoTr.
Demonstration below (with some extraneous code and layout removed):
function deletar(tr) {
var tabela = document.getElementById('myTable');
tabela.deleteRow(tr.rowIndex);
}
var botaoAdd = document.getElementById("adicionar-contato");
botaoAdd.addEventListener("click", addContato);
function addContato(event) {
event.preventDefault();
//Criando uma tr
var contatoTr = document.createElement("tr");
var formContato = document.getElementById("formulario");
//Criando 06 tds
var nomeTd = document.createElement("td");
var emailTd = document.createElement("td");
var celularTd = document.createElement("td");
var instaTd = document.createElement("td");
var faceTd = document.createElement("td");
var excluirTd = document.createElement("td");
//Preenchendo as Tds
nomeTd.textContent = formContato.nome.value;
emailTd.textContent = formContato.email.value;
celularTd.textContent = formContato.cel.value;
instaTd.textContent = formContato.insta.value;
faceTd.textContent = formContato.face.value;
excluirTd.innerHTML = "<button class='btn btn-danger excluir'><i class='fa fa-trash-o' >Excluir</i></button>";
contatoTr.appendChild(nomeTd);
contatoTr.appendChild(emailTd);
contatoTr.appendChild(celularTd);
contatoTr.appendChild(instaTd);
contatoTr.appendChild(faceTd);
contatoTr.appendChild(excluirTd);
// attach the "delete" action to this button for this row
excluirTd.querySelector('button').addEventListener("click", () => {
deletar(contatoTr)
})
var agendaTabela = document.getElementById("corpoAgenda");
agendaTabela.appendChild(contatoTr);
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
<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>
<div class="salvarexcluir">
<button type="button" class="btn btn-info" id="adicionar-contato">Salvar</button>
</div>
</form>
</div>
<!-- Tabela que conterá os dados-->
<div class="container mt-3">
<table class="table table-striped" id="myTable">
<thead>
<tr>
<th>Nome</th>
<th>Email</th>
<th>Celular</th>
<th>Instagram</th>
<th>Facebook</th>
<th>Excluir</th>
</tr>
</thead>
<tbody id="corpoAgenda">
</tbody>
</table>
</div>
When a click event occurs on a table, I want to pass the values of the relevant row into the modal. I wrote a code like this, but the values of the top row are always passed into the modal. What I want to do is to show the values in the row I clicked in the modal. How can I provide this?
my table codes here:
<table class="table align-middle" id="customerTable">
<thead class="table-light">
<tr>
<th class="sort" data-sort="name">Name Surname</th>
<th class="sort" data-sort="company_name">Phone Number</th>
<th class="sort" data-sort="leads_score">Note</th>
<th class="sort" data-sort="phone">Status</th>
<th class="sort" data-sort="location">Personal Name</th>
<th class="sort" data-sort="tags">Data Name</th>
<th class="sort" data-sort="action">Edit</th>
</tr>
</thead>
<tbody class="list form-check-all">
{% for x in model %}
<tr>
<td class="table-namesurname">{{x.name}}</td>
<td class="table-phonenumber">{{x.phonenumber}}</td>
<td class="table-note">{{x.note}}</td>
<td class="table-status">{{x.status}}</td>
<td class="table-callname">{{x.callname}}</td>
<td class="table-dataname">{{x.dataname}}</td>
<td>
<ul class="list-inline hstack gap-2 mb-0">
<li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Edit">
<a class="edit-item-btn" id="call-button" href="#showModal" data-bs-toggle="modal" data-id="{{x.id}}"><i class="ri-phone-line fs-16"></i></a> <!-- Here is the edit button -->
</li>
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
my modal here
<div class="modal fade" id="showModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-light p-3">
<h5 class="modal-title" id="exampleModalLabel"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="close-modal"></button>
</div>
<form action="">
<div class="modal-body">
<input type="hidden" id="id-field" />
<div class="row g-3">
<div class="col-lg-12">
<div>
<label for="company_name-field" class="form-label">Name Surname</label>
<input type="text" id="call-name-surname" class="form-control" placeholder="Enter company name" value="" required />
</div>
</div>
<div class="col-lg-12">
<div>
<label for="company_name-field" class="form-label">Phone Number</label>
<input type="email" id="call-phone-number" class="form-control" placeholder="Enter company name" value="" required />
</div>
</div>
<!--end col-->
<div class="col-lg-12">
<div>
<label for="leads_score-field" class="form-label">Note</label>
<input type="text" id="call-note-field" class="form-control" placeholder="Enter lead score" value="" required />
</div>
</div>
<!--end col-->
<div class="col-lg-12">
<div>
<label for="phone-field" class="form-label">Status</label>
<input type="text" id="call-status-field" class="form-control" placeholder="Enter phone no" value="" required />
</div>
</div>
<div class="col-lg-12">
<div>
<label for="phone-field" class="form-label">Personal Name</label>
<input type="text" id="call-persnoel-name" class="form-control" placeholder="Enter phone no" value="" required />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="hstack gap-2 justify-content-end">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Kapat</button>
<button type="submit" class="btn btn-success" id="add-btn">Kaydet</button>
</div>
</div>
</form>
</div>
</div>
</div>
and the my script codes
<script type="text/javascript">
$(document).ready(function () {
$("#call-button").click(function() {
var nameSurname = $(this).closest('tr').find('.table-namesurname').text();
var phoneNumber = $(this).closest('tr').find('.table-phonenumber').text();
var note = $(this).closest('tr').find('.table-note').text();
var status = $(this).closest('tr').find('.table-status').text();
var callName = $(this).closest('tr').find('.table-callname').text();
var dataName = $(this).closest('tr').find('.table-dataname').text();
$("#call-name-surname").val(nameSurname)
$("#call-phone-number").val(phoneNumber)
$("#call-note-field").val(note)
$("#call-status-field").val(status)
$("call-persnoel-name").val(callName)
});
});
</script>
console output
Gökan 905387532589 <empty string> Aranmadı ece datatest
The problem here is that the values of the clicked element in the table are not coming. Whichever I click, the values of the element at the top of the table are displayed. How can I solve this problem?
HTML id attribute should be unique, adding multiple elements with the same id, when you select, you will only get the first element that has this id, you need to select the rows by class, you have edit-item-btn class for the button.
<script type="text/javascript">
$(document).ready(function () {
$(".edit-item-btn").click(function() {
var nameSurname = $(this).closest('tr').find('.table-namesurname').text();
var phoneNumber = $(this).closest('tr').find('.table-phonenumber').text();
var note = $(this).closest('tr').find('.table-note').text();
var status = $(this).closest('tr').find('.table-status').text();
var callName = $(this).closest('tr').find('.table-callname').text();
var dataName = $(this).closest('tr').find('.table-dataname').text();
$("#call-name-surname").val(nameSurname)
$("#call-phone-number").val(phoneNumber)
$("#call-note-field").val(note)
$("#call-status-field").val(status)
$("call-persnoel-name").val(callName)
});
});
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 am working on a piece of code and since I dont have too much experience with jquery or javascript I need your help. I want to take the data from the row when button EditBtn is clicked and set those values to modal. I tried the code below but It was not working.
Below is my code
Table :
<table id="example" class="table table-bordered table-hover">
<thead>
<tr>
<th>Ödeme Türü</th>
<th>Ödeme Başlığı</th>
<th>İçerik</th>
<th>Son Ödeme Tarihi</th>
<th>Tutarı</th>
<th>Ödeme Durumu</th>
<th>Düzenle</th>
</tr>
</thead>
<tbody>
#foreach (OdemeList item in Model)
{
<tr id="#item.Odeme.OdemeID">
<td>#item.Odeme.OdemeType</td>
<td>#item.Odeme.OdemeTitle</td>
<td>#item.Odeme.OdemeContent</td>
<td>#item.Odeme.SonOdemeTarih</td>
<td>#item.Odeme.OdemeTutar</td>
#if (#item.KullaniciOdeme.isPay == true)
{
<td>Odendi</td>
}
else
{
<td>Odenmedi</td>
<td>
<form>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_6pRNASCoBOKtIshFeQd4XMUh"
data-amount="#item.Odeme.OdemeTutar"
data-name="#item.Odeme.OdemeTitle"
data-image="/Content/LoginCssJs/pay.png"
data-locale="auto">
</script>
</form>
</td>
#*<td>
<a data-toggle="modal" data-target=".bootstrapmodal3"><button class="btn btn-success">Öde</button></a>
</td>*#
}
<td>
<a data-toggle="modal" id="EditBtn" class="btn edit" data-target=".bootstrapmodal"><img src="#Url.Content("~/Content/Icons/edit.png")" alt="Düzenle" /></a>
</td>
<td>
<a data-toggle="modal" data-target=".bootstrapmodal2"><img src="#Url.Content("~/Content/Icons/Delete.png")" alt="Sil" /></a>
</td>
</tr>
}
</tbody>
</table>
My modal:
<div class="modal fade bootstrapmodal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button data-dismiss="modal" class="close"><span>×</span></button>
<div class="modal-title">
<h3>Ödeme Düzenle</h3>
</div>
</div>
<div class="modal-body">
<form>
<label>Ödeme Türü</label>
<select class="form-control" id="OdemeTuru">
<option>Aidat</option>
<option>Isınma</option>
<option>Bina Gideri</option>
</select><br />
<div class="form-group">
<label for="odemebasligi">Ödeme Başlığı</label>
<input type="text" class="form-control" id="odemebasligi" placeholder="OdemeTitle">
</div>
<div class="form-group">
<label for="comment">Ödeme içeriği</label>
<textarea class="form-control" rows="5" id="comment" placeholder="-OdemeContent"></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Tutar</label>
<div class="input-group">
<div class="input-group-addon">TL</div>
<input type="text" class="form-control" id="exampleInputAmount" placeholder="OdemeTutar">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label for="odemetarihi">Son Ödeme Tarihi</label>
<input type="text" class="form-control" id="odemetarihi" placeholder="SonOdemeTarih">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary">Kaydet</button>
<button class="btn btn-danger" data-dismiss="modal"> Vazgeç</button>
</div>
</div>
</div>
</div>
Script:
<script>
$('a.edit').on('click', function() {
var myModal = $('.bootstrapmodal');
//// now get the values from the table
//var OdemeTuru = $(this).closest('tr').find('td.OdemeType').html();
var OdemeBaslik = $(this).closest('tr').find('td.OdemeTitle').html();
var OdemeIcerik = $(this).closest('tr').find('td.OdemeContent').html();
var OdemeTutar = $(this).closest('tr').find('td.SonOdemeTarih').html();
var SonOdemeTarihi = $(this).closest('tr').find('td.OdemeTutar').html();
//// and set them in the modal:
//$('#', myModal).val(OdemeTuru);
$('#odemebasligi', myModal).val(OdemeBaslik);
$('#comment', myModal).val(OdemeIcerik);
$('#exampleInputAmount', myModal).val(OdemeTutar);
$('#odemetarihi', myModal).val(SonOdemeTarihi);
// and finally show the modal
myModal.modal({ show: true });
return false;
});
</script>
In script you are targeting <td> class .find('td.OdemeTitle') and in table there are no class defined <td>#item.Odeme.OdemeTitle</td> what you only need is define class which you are targeting e.g
For
var OdemeBaslik = $(this).closest('tr').find('td.OdemeTitle').html();
HTML
<td class="OdemeTitle">#item.Odeme.OdemeTitle</td>
follow above example and set all <td> classes and you will be all set.
minimal fiddle example