Home > front end >  Block duplicate data in table Javascript
Block duplicate data in table Javascript

Time:11-12

I want to block equal data entry in the phone number.

I tried several methods and failed.

I changed the code several times and I couldn't.

`const form = document.getElementById('agenda-de-contatos');
let linhas = [];
form.addEventListener('submit', function (e) {
    e.preventDefault();
    const inputNomeContato = document.getElementById('nome-do-contato');
    const inputNumeroTelefone = document.getElementById('numero-de-telefone');
    
    if (linhas.includes(inputNumeroTelefone.value)) {
        alert(`Número: ${inputNumeroTelefone.value} já foi inserido`);
    } else {
        linhas.push(inputNumeroTelefone.value);
    }
        
    let linha = '<tr>';
    linha  = `<td>${inputNomeContato.value}</td>`;
    linha  = `<td>${inputNumeroTelefone.value}</td>`;
    linha  = `<td><button class='excluir' onclick="deleteRow(this.parentNode.parentNode.rowIndex,this)">Remover</button></td>`;
    linha  = '</tr>';
    
    linhas.push(linha);
     
    const corpoTabela = document.querySelector('tbody');
    corpoTabela.innerHTML = linhas.join("")
})
 
function deleteRow(id,node) {
   
 linhas.splice(id-1,1);
    document.getElementById('tabela').deleteRow(id);
  
}`


CodePudding user response:

There was a little confusion in your script, as to what you want to keep in linhas. You pushed both, a phone number and a whole <tr>-html code into it. I changed it so that you only have the telephone numbers in it (your HTML markup was missing, so I just made it up):

const form = document.getElementById('agenda-de-contatos'),
  corpoTabela = document.querySelector('tbody'),
  linhas = [];

corpoTabela.onclick=ev=>{
 if (ev.target.tagName=="BUTTON"){
   const tr=ev.target.closest("tr");
   linhas.splice(tr.rowIndex-1,1);
   tr.remove();
   console.log(linhas);
}}

form.addEventListener('submit', function(e) {
  e.preventDefault();
  const inputNomeContato = document.getElementById('nome-do-contato');
  const phoneInp = document.getElementById('numero-de-telefone').value, phone=phoneInp.replace(/[\s()-]/g,"");

  if (linhas.includes(phone)) {
    alert(`Número: ${phoneInp} já foi inserido`);
  } else {
    linhas.push(phone);
    corpoTabela.insertAdjacentHTML("beforeend", `<tr>
    <td>${inputNomeContato.value}</td>
    <td>${phoneInp}</td>
    <td><button class='excluir'>Remover</button></td>
   </tr>`);
   console.log(linhas);
  }
})
<form id="agenda-de-contatos">
  <input id="nome-do-contato" placeholder="Name?"><input id="numero-de-telefone" placeholder="Phone number?">
  <button>submit</button>
</form>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Phone Number</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

After reading @EssXTee's comment regarding the formatting of phone numbers I decided to sanitise the input values before pushing them onto linhas:

phone=phoneInp.replace(/[\s()-]/g,"")

This should make the comparison a little more robust.

CodePudding user response:

The only real issue with your code not working is that you just need to exit your function when you detect a duplicate phone number. It seems your code currently alerts if a duplicate number is detected, but because there is no return statement, the function will continue to execute code (thus adding the new entry to the table).

There are a few other things that could be adjusted with your code, like tacoshy mentioned you don't need to concatenate a new string variable when using backticks. Another seems to be that your deleteRow() function doesn't work (and appears to call itself which could be bad).

Your HTML was not provided so I included the bare minimum for a code snippet to show the fixes.

let linhas = []

document.getElementById('agenda-de-contatos').addEventListener('submit', e => {
  e.preventDefault()

  const inputNomeContato = document.getElementById('nome-do-contato'),
        inputNumeroTelefone = document.getElementById('numero-de-telefone')

  if(linhas.some(l => l.includes(inputNumeroTelefone.value))) {
    alert(`Número: ${inputNumeroTelefone.value} já foi inserido`)
    return
  }

  linhas.push(`<tr>
      <td>${inputNomeContato.value}</td>
      <td>${inputNumeroTelefone.value}</td>
      <td><button class='excluir' onclick="deleteRow(this)">Remover</button></td>
    </tr>`)

  document.querySelector('tbody').innerHTML = linhas.join("")
})

function deleteRow(id) {
  linhas.splice(id.parentNode.parentNode.rowIndex,1)
  document.querySelector('tbody').innerHTML = linhas.join("")
}
<form id="agenda-de-contatos">
  <input id="nome-do-contato" type="text" placeholder="Name"><br>
  <input id="numero-de-telefone" type="text" placeholder="Phone Number"><br>
  <input type="submit">
</form>

<table>
  <tbody></tbody>
</table>

NOTES

One unusual thing I noticed is that you are pushing both the phone number and your HTML into the same array. I'm not sure if that is intentional because it causes your phone number to display twice (once above the row and once properly in the actual table column). You could just use 2 arrays (one with the phone numbers only and one with the HTML), however you are able to just store the HTML and check if that contains duplicate phone numbers using some() on the array.

  • Related