Reputation: 29
I have the following table on my page:
<section class="content">
<div class="box">
<div class="box-header with-border">
<div class="row margin-bottom-20">
<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 text-end">
<a href="#" title="Novo Cadastro" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#InsertProduct"> <i class="fa fa-plus"> </i>New </a>
</div>
</div>
</div>
</div>
<table class="table table-striped" id="QueryTable">
<thead>
<tr>
<th>Code: </th>
<th class="text-center">Name: </th>
<th class="text-center">Address: </th>
<th class="text-center">Phone: </th>
<th class="text-center">Options: </th>
</tr>
</thead>
<tbody>
<td>Code: </td>
<td class="text-center">Name: </td>
<td class="text-center">Address: </td>
<td class="text-center">Phone: </td>
<td class="text-center">Options: </td>
</tbody>
</table>
</section>
I need to insert rows and columns into this table via javascript. I tried something like:
$('#QueryTable').find('tr').each(function(){
$(this).find('th').eq(n).after('<th>Test </th>');
});
I also tried
$('#QueryTable tr').append('<th>Test</th>')
I also tried 02:
$('#QueryTable tr').each(function()
{
$(this).append('<th>Test</th>');
});
But these codes did not insert a row or column in my table. How do I add rows and columns by javascript (pure or jquery)?
Upvotes: 0
Views: 891
Reputation: 17380
Here is a simple example. I first fixed your table so that your cells are inside a row:
//adds the new column
$('#QueryTable thead tr').append('<th>Test</th>');
//adds a new cell to all existing rows (this assumes that the newly added column does not exist)
//at initialization
$('#QueryTable tbody tr').each(function() {
$(this).append('<td>New Cell</td>');
});
//Adds a new row
$('#QueryTable tbody').append('<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped" id="QueryTable">
<thead>
<tr>
<th>Code: </th>
<th class="text-center">Name: </th>
<th class="text-center">Address: </th>
<th class="text-center">Phone: </th>
<th class="text-center">Options: </th>
</tr>
</thead>
<tbody>
<tr>
<td>Code: </td>
<td class="text-center">Name: </td>
<td class="text-center">Address: </td>
<td class="text-center">Phone: </td>
<td class="text-center">Options: </td>
</tr>
</tbody>
</table>
Upvotes: 1