Reputation: 5854
I have a simple table with 5 rows. 1st row is only visible and last 4row are hidden.
<table>
<tr>
<th>sr</th>
<th>Head</th>
</tr>
<tr style="display:block;">
<td>1</td>
<td>row 1</td>
</tr >
<tr style="display:none;">
<td>2</td>
<td>row 2</td>
</tr>
<tr style="display:none;">
<td>3</td>
<td>row 3</td>
</tr>
<tr style="display:none;">
<td>4</td>
<td>row 4</td>
</tr>
<tr style="display:none;">
<td>5</td>
<td>row 5</td>
</tr>
</table>
<button id="add">Add row</button>
<button>Remove row</button>
javascript what i have try
$('#add').click(function() {
rows.show();
});
When click on add row the 2nd row should show and so no and when click on remove row it should hide the latest row and so on
Upvotes: 0
Views: 2565
Reputation: 12085
Just find the first hidden tr
using and last visible tr
like this
$(document).on('click','#add',function(){
$('table tbody').find('tr:hidden:first').show();
});
$(document).on('click','#remove',function(){
$('table tbody').find('tr:visible:last:not(:first-child)').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>sr</th>
<th>Head</th>
</tr>
<tbody>
<tr style="display:block;">
<td>1</td>
<td>row 1</td>
</tr >
<tr style="display:none;">
<td>2</td>
<td>row 2</td>
</tr>
<tr style="display:none;">
<td>3</td>
<td>row 3</td>
</tr>
<tr style="display:none;">
<td>4</td>
<td>row 4</td>
</tr>
<tr style="display:none;">
<td>5</td>
<td>row 5</td>
</tr>
</tbody>
</table>
<button id="add">Add row</button>
<button id="remove">Remove row</button>
Upvotes: 1
Reputation: 1423
Check if below code works!
I have added id to add and remove buttons.
$('#btnAdd').click(function () {
$("table tr:hidden:first").show();
});
$('#btnRemove').click(function () {
if($("table tr:visible").length !== 2) {
$("table tr:visible:last").hide();
}
});
Upvotes: 1
Reputation: 2147
You could change your buttons
<button data-action="add">Add row</button>
<button data-action="remove">Remove row</button>
and now you can use this script
$(document).ready(function() {
$('button[data-action]').on('click', function() {
// which button is pressed?
if ($(this).data('action') == 'add') {
// show 'tr' of all 'td'
$('table td').parent().css('display', 'block');
} else {
// hide'tr' of all 'td'
$('table td').parent().css('display', 'none');
}
});
});
Change your table rows
<tr style="height: 0px;">
<td>5</td>
<td>row 5</td>
</tr>
Now you can use this
$(document).ready(function() {
$('button[data-action]').on('click', function() {
// which button is pressed?
if ($(this).data('action') == 'add') {
// show 'tr' of all 'td'
$('table td').parent().collapse('show');
} else {
// hide'tr' of all 'td'
$('table td').parent().collapse('hide');
}
});
});
Upvotes: 0
Reputation: 5012
You can use this jQuery function to find hidden tr:
var hiddenTRs = $("tr:hidden");
then you can show of of them with:
hiddenTRs.first().show();
Upvotes: 0