0

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 class="col-4">
    <div class="form-group">
        <label asp-for="Quantite" class="control-label"></label>
        <input asp-for="Quantite" class="form-control" id="quantite" />
        <span asp-validation-for="Quantite" class="text-danger"></span>
    </div>
</div>

<button type="button" class="btn btn-primary"  onclick="AddRows()">Add articles</button>

<table class="table table-bordered" 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?

Lain
  • 3,657
  • 1
  • 20
  • 27
user4374239
  • 93
  • 2
  • 11
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"**Describe the problem.** "It doesn't work" isn't descriptive enough to help people understand your problem. Instead, tell other readers what the expected behavior should be. Tell other readers what the exact wording of the error message is, and which line of code is producing it. Use a brief but descriptive summary of your problem as the title of your question."_ – Andreas Oct 24 '22 at 09:33
  • If you "Inspect" the DOM after you click the button you will see that the rows are inserted. But only empty rows, without any cells. – Andreas Oct 24 '22 at 09:35
  • It does insert rows. But firstly those are in `thead` and secondly you can not see those due to lack of content. Check out [`insertRow`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow) – Lain Oct 24 '22 at 09:35
  • whats inside insertRow() that may discribe your issue more and you are selecting table tag but you should set id to tbody tag and create a selector to it bcz you needed your rows there. – mzaifquraishi Oct 24 '22 at 09:38
  • Yes when i "inspect" i found that rows are inserted but in "thead" not in "tbody" – user4374239 Oct 24 '22 at 09:39
  • `insertRow` takes a parameter, when passing -1, the newly-created row is appended to the table. It's also better to append directly to `tbody` instead of `table`. – Teemu Oct 24 '22 at 09:59

0 Answers0