Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
Adding new table row after td's full

After seventh day, new table row should be added. And if the user add new value it should be added td which added recently. The frustrating point is, I don't know how to manipulate DOM's for this situation.

  const workInput = document.querySelector('#workInput')
    const workForm = document.querySelector('#workForm')
    const workBtn = document.querySelector('#workButton')
    const tableTd = document.querySelectorAll('table tbody tr td')
    const tableTr = document.querySelectorAll('table tbody tr')
    workForm.addEventListener('submit', (e)=>{
        tableTr.forEach(function(tr){
            tr.innerHTML+=
            `  <td>${workInput.value}</td>   `
        })
       e.preventDefault()
    })


    table{
        margin: 1rem auto;
        width: 1000px;
        background-color: rgb(54, 180, 238);
    }
    tr{
        background-color: aliceblue;
    }
    tr:nth-child(odd){
        background-color: antiquewhite; 
    }
    td{
        text-align: center;
    }



      <div>
           <form autocomplete="off" action="#" id="workForm">
            <input type="text" id="workInput">
            <button id="workButton">Add</button>
           </form>
            <table>
                <thead>
                  <tr>
                    <th>First day</th>
                    <th>Second day</th>
                    <th>Third day</th>
                    <th>Fourth day</th>
                    <th>Fifth day</th>
                    <th>Sixth day</th>
                    <th>Seventh day</th>
                  </tr>
                </thead>
                <tbody>
                    <tr></tr>
                </tbody>
            </table>
        </div>

I tried many ways for that, couldn't find properly method. Many forEach algorithms, DOM manipulation, but still I have no idea. Any idea for that situation? Btw, I need to create with vanilla js, not any plugin, or Jquery. Hope, everything is clear, if not just comment for more details, please. Thanks for all responses.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

   // i added 
  let days = 7;
  let workCount = 0;


  const workInput = document.querySelector("#workInput");
  const workForm = document.querySelector("#workForm");
  const workBtn = document.querySelector("#workButton");
  const tableTd = document.querySelectorAll("table tbody tr td");
  
  // I changed it from const to let and querySelectorAll all to querySelectorA
  let tableTr = document.querySelector("table tbody tr");

  const tableBody = document.querySelector("table tbody");

  workForm.addEventListener("submit", (e) => {
    e.preventDefault();
    if (workCount < days) {
      tableTr.innerHTML += `<td>${workInput.value}</td>`;
      workCount++;
    }
    if (workCount === days) {
      workCount = 0;
      let newRow = document.createElement("tr");
      tableTr = newRow;
      tableBody.appendChild(newRow);
    }
  });
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use childElementCount to check the number of elements in a row and use appendChild to add a new row.

HTML code

    <div>
      <form autocomplete="off" id="workForm">
        <input type="text" id="workInput" />
        <button id="workButton" onclick="onSubmitWork()">Add</button>
      </form>
      <table>
        <thead>
          <tr>
            <th>First day</th>
            <th>Second day</th>
            <th>Third day</th>
            <th>Fourth day</th>
            <th>Fifth day</th>
            <th>Sixth day</th>
            <th>Seventh day</th>
          </tr>
        </thead>
        <tbody id="tbody">
          <tr class="row0"></tr>
        </tbody>
      </table>
    </div>

JS code

// handle submit button
function onSubmitWork() {
  // Get input element by id
  const workInput = document.getElementById('workInput');

  // Get tbody element
  const tbody = document.getElementById('tbody');

  // Get total rows "tr"
  const nbRows = tbody.childElementCount;

  // Get cuurent row by css class name
  const currentRow = document.querySelector(`.row${nbRows - 1}`);
  console.log(currentRow.childElementCount);

  // Check the number of td we have in the current row
  if (currentRow.childElementCount <= 5) {
    addWork(workInput.value, nbRows);
  } else {
    addRow(nbRows);
    addWork(workInput.value, nbRows);
  }
}

// Add a new "td"
function addWork(inputValue, nbRows) {
  let node = document.createElement('TD');
  const text = document.createTextNode(inputValue);
  node.appendChild(text);

  const row = document.querySelector(`.row${nbRows - 1}`);
  row.appendChild(node);
}

// Add a new row "tr"
function addRow(nbRows) {
  let row = document.createElement('TR');

  // Create a new css clss name for the new row
  const rowClass = `row${nbRows}`;
  row.classList.add(rowClass);
  document.getElementById('tbody').appendChild(row);
}

here is a demo

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda