How to remove row from a JavaScript dynamic table? - javascript

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>

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 :)

How can I pass the values of the relevant row into the modal when a click event occurs on a table?

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

How to copy full form on click add button(+ plus)

I am trying to copy full form on click add button,
copying only label name.
below JS code: below is js code trying to add form dynamically.
how to add same form below last div onclick '+' button.
using js code below, only adding panel, but it's not working.
document.getElementById('add').onclick = duplicate;
var i = 0;
var original = document.getElementById('add-form');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "add-form" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
<div class="row mt-4">
<div class="row">
<div class="col-md-3 text-center mt-3 ml-3">
<button type="button" class="btn btn-light" id="add"><i class="fas fa-plus fa-xs"></i></button>
</div>
<div class="col-md-3 text-center mt-3 ml-4">
<button type="button" class="btn btn-light" id="minus"><i class="ri-delete-bin-line mr-0"></i></button>
</div>
</div>
<div class="col-md mt-1" id="add-form" style="width: 100%;">
<button class="accordion btn btn-primary">Product screen</button>
<div class="panel">
<div class="col-sm-12">
<div class="card mt-3">
<div class="col-md-12">
<!-- first row -->
<div class="row" style="margin-top: 9px;">
<div class="col-sm">
<label for="fname">product_name
</label>
<input type="text" id="fname" class="form-control" placeholder="product_name">
</div>
<div class="col-sm">
<label for="fname">price
</label>
<input type="text" id="fname" class="form-control" placeholder="price">
</div>
<div class="col-sm">
<label for="fname">pur_id
</label>
<input type="text" id="fname" class="form-control" placeholder="pur_id">
</div>
<div class="col-sm">
<label for="field2">type
</label>
<select name="field2" id="field2" class="selectpicker form-control" data-style="py-0" width="50">
<option selected>select one</option>
<option>type1</option>
<option>type2</option>
<option>type3</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
after click add button displayed only this panel.

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 do i fix an insertBefore() error in JS

<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
<i class="fas fa-car text-success"></i>
My<span class="text-success ">Car</span>List</h1>
<form id="car-form">
<div class="form-group">
<label for="worker">Empoloyee ID</label>
<input type="text" id="worker" class="form-control">
</div>
<div class="form-group">
<label for="carVin">Car Vin</label>
<input type="text" id="carVin" class="form-control">
</div>
<div class="form-group">
<label for="strTime">Start time</label>
<input type="text" id="strTime" class="form-control">
</div>
<div class="form-group">
<label for="endTime">End time</label>
<input type="text" id="endTime" class="form-control">
</div>
<input type="submit" value="Add Car" class="btn btn-primary btn-block">
</form>
</body>
<div class="container mt-4">
<h1 class="display-4 text-center">
<i class="fas fa-car text-success"></i>
My<span class="text-success ">Car</span>List</h1>
<form id="car-form">
<div class="form-group">
<label for="worker">Empoloyee ID</label>
<input type="text" id="worker" class="form-control">
</div>
<div class="form-group">
<label for="carVin">Car Vin</label>
<input type="text" id="carVin" class="form-control">
</div>
<div class="form-group">
<label for="strTime">Start time</label>
<input type="text" id="strTime" class="form-control">
</div>
<div class="form-group">
<label for="endTime">End time</label>
<input type="text" id="endTime" class="form-control">
</div>
<input type="submit" value="Add Car" class="btn btn-primary btn-block">
</form>
<table class="table table-striped table-hover table-dark mt-3">
<thead>
<tr>
<th>Employee ID</th>
<th>Car Vin</th>
<th>Start time</th>
<th>End time</th>
<th></th>
</tr>
</thead>
<tbody id="car-list"></tbody>
</table>
<!div id="my-filter" class="msg" >
<!input type="submit" value="Filter Car" class="btn btn-primary btn-block">
</div>
I'm setting a new div used to display error messages for my program using the insertBefore() method, but it doesn't seem to be working. How would I fix this?
What do I need to change?
class UI {
static displayCars(){}
static addCarToList(car){
const list = document.querySelector('#car-list');
const row = document.createElement('tr');
row.innerHTML = `
<td>${car.worker}</td>
<td>${car.carVin}</td>
<td>${car.strTime}</td>
<td>${car.endTime}</td>
<td><a href="#" class="btn btn-danger btn-sm
delete">Clear</a></td>`;
list.appendChild(row);
}
static showAlert(message, className){
const div =document.createElement('div');
div.className = `alert alert-${className}`;
div.appendChild(document.createTextNode(message));
const container = document.querySelector('.container');
const form = document.querySelector('#car-form');
// before(newnode, existingnode)
// IM HAVING THE ERROR LINE 49
container.insertBefore(div, form);
// Vanish in 3 secs
setTimeout(() => document.querySelector('.alert').remove(),3000);
}
}
The program would display the car array but it would not do the alert message on line 111
if(worker === ''|| carVin === ''|| strTime === '' || endTime === ''){
UI.showAlert('Please fill all fields', 'danger'); //LINE 111
} else {
// Instatiate car
const car = new Car(worker, carVin, strTime, endTime);
// Add car to list
// UI.addCarToList(car); ///
// Add car to local storage
Store.addCar(car);
UI.displayCars(); ///
// Show Success msg
UI.showAlert('Car Added', 'success');
//Clear fields
UI.clearFields();
}
[![ERROR DESCRIPTION][2]][2]
app.js:56 Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
at Function.showAlert (file:///C:/Users/awbak/Desktop/WEBSITES/My%20Car%20List/app.js:56:13)
at HTMLFormElement. (file:///C:/Users/awbak/Desktop/WEBSITES/My%20Car%20List/app.js:120:6)
[1]: https://i.stack.imgur.com/G1yIM.png
[2]: https://i.stack.imgur.com/koiYh.png
As your error states, your form is not inside the container. The referenceNode, so the form, needs to be inside of the container,
insertBefore reference

Categories

Resources