Home > Enterprise >  Insert multiple rows to a table using Javascript
Insert multiple rows to a table using Javascript

Time:10-24

I'm trying to insert multiple rows to a table based on an input value, i used this code but it doesn't work:

function AddRows() {
    var RowNumber = document.getElementById('quantite').value;

    var table = document.getElementById('articleTable');
    for (var i = 0; i < RowNumber; i  )
    {
        table.insertRow();
    };

}
<div >
    <div >
        <label asp-for="Quantite" ></label>
        <input asp-for="Quantite"  id="quantite" />
        <span asp-validation-for="Quantite" ></span>
    </div>
</div>

<button type="button"   onclick="AddRows()">Add articles</button>

<table  id="articleTable" style="margin-top:10px;">
    <thead>
        <tr>
            <th>Numero de Serie</th>
            <th>Marque</th>
            <th>Etat</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
 </table>

So what's wrong in my code or is there any better way to add rows to html table based on an input value?

CodePudding user response:

It is generally not a good idea to use inline event handlers. There a several ways to insert rows into a table. This snippet uses event delegation and Element.insertAdjacentHTML to add a row into into the table body. It may help you further.

document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.classList.contains(`btn-primary`)) {
    document.querySelector(`#articleTable tbody`).insertAdjacentHTML(`beforeend`,
      `<tr>
         <td>${document.getElementById('quantite').value.trim() || 'no value'}</td>
         <td>[-]</td>
         <td>[-]</td>
       </tr>`);
  }
}
<div >
  <div >
    <label asp-for="Quantite" ></label>
    <input asp-for="Quantite"  id="quantite" />
    <span asp-validation-for="Quantite" ></span>
  </div>
</div>

<button type="button" >Add articles</button>

<table  id="articleTable" style="margin-top:10px;">
  <thead>
    <tr>
      <th>Numero de Serie</th>
      <th>Marque</th>
      <th>Etat</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

CodePudding user response:

this is not clear enough we need a very clear explanation

  • Related