Show only a limited number of rows in a table - javascript

I am trying to limit the number of rows displayed in a <table>. I need to show only 2 rows out of whatever number of records fetched. There's a small button at the end of the table, on click of which the rest of the records will get revealed.
Here's a sample screenshot of how the table will look like.
I have tried searching over SO and other websites, but unable to get through. I can't use any jQuery plugin for table either.
How can I achieve this using jQuery/JavaScript?

Select tr elements from tbody and use slice method to select a range of them:
$("table > tbody > tr").hide().slice(0, 2).show();
Demo:
$("table > tbody > tr").hide().slice(0, 2).show();
$(".show-all").on("click", function() {
$("tbody > tr", $(this).prev()).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>1</td>
<td>Alice</td>
</tr>
<tr>
<td>2</td>
<td>Bob</td>
</tr>
<tr>
<td>3</td>
<td>Carol</td>
</tr>
</tbody>
</table>
<button class="show-all">Show all</button>
.slice( start [, end ] )
Reduce the set of matched elements to a subset specified by a range of indices.
start
Type: Integer
An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.
end
Type: Integer
An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.

You can use :gt selector to target other rows having index greater than 2 and then hide them:
$('table tr:gt(1)').hide();// :gt selector has 0 based index

This is how I did it:
<script>
$(document).ready(function () {
$('table tr:gt(10)').hide();
});
function showAllRows() {
$('table tr').show();
}
</script>
Then the button for show all:
<button onclick="showAllRows()">Show all</button>

Related

Removing text within an element that is after the first <br>, but before the second <br> on each relevant row

I have text in a table cell that has 3 text blocks separated by <br>. I need to keep the first of these for each time the same row appears in a table.
/* JQuery loop */
$('.invoiceTable > tbody > tr').each(function() {
title = $("tr.invoiceTableCatalog td").html().split("<br>")[0];
$("tr.invoiceTableCatalog td:first").replaceWith( '<td>'+title+'</td>' );
});
/* Javascript loop */
[].forEach.call(document.querySelectorAll('.invoiceTable > tbody > tr'), function(tr) {
title = $(".invoiceTableCatalog td").html().split("<br>")[0];
$(".invoiceTableCatalog td:first").replaceWith( '<td>'+title+'</td>' );
});
However The first row for the occurrence changes, not the other rows.
Here is the HTML for the row:
<tr class="invoiceTableDetail invoiceTableCatalog">
<td class="invoiceTableItem" style="width:40%;" valign="top">
Multibooking discount
<br>This is a multibooking discount for being kind enough to buy lots of courses with us - thanks
<br>(based on -20 Percent of Total Price)
</td>
</tr>
I'd have expected that each row would have the content replaced, but no, it is not ;-(
Thanks in advance for any assistance.

jQuery- How to select a element with class name from a list of elements

I am using jQuery.
I want to select a cell from a table.
So I tried the following codes.
// First line works fine for me. I can get a list of columns at the correct target row.
var targetColumns = $(elemClicked).closest("tr").find("td");
// I want to get the cell with the class named "draftstatus". This line has problem. I cannot get what I want.
var targetCell = columnsAtTargetRow.$(".draftstatus");
The targetColumns inspected from browser looks like the following:
The 5th td above is my target cell.
I also try to use find() function. It won't work either because find() will start from next children level.
columnsAtTargetRow.find(".draftstatus"); // this does not work.
What functions should I used to get that cell within that "list of td".
Thanks in advance.
You just need to figure out which selectors to use.
var targetColumns = $(elemClicked).closest("tr").find("td");
this goes up the DOM to the "tr" and selects the tds. If the elemClicked is inside a td you can select the tds with closest("td"), and then use siblings(".draftstatus");
If the elemClicked is a td, then you can just use siblings(".draftstatus");
Here is some example code to help demonstrate some selectors. Hope this helps some and not confused you more.
$(function(){
//reference all cells with myclass class using filter
$("#table1 tbody td").filter(".myclass").addClass("red");
// click events for all tds reference the .target class cell using siblings
$("#table1 tbody td").on("click",function(e){
$(this).siblings(".target").toggleClass("red");
});
//items inside a table cell click event
$("#table1 tbody td a").on("click",function(e){
//toggle bold class
$(this).closest("td").siblings(".target").toggleClass("bold");
//prevent event from bubbling up
e.stopPropagation();
});
})
.red {
background-color:red;
}
.bold { font-weight:bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1" id="table1">
<tbody>
<tr>
<td>foo</td>
<td>bar</td>
<td class="myclass target">value2</td>
<td>Two link</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td class="myclass target">value2</td>
<td>Two link</td>
</tr>
</tbody>
</table>
This is incorrect:
columnsAtTargetRow.$(".myclass");
This should be:
columnsAtTargetRow.find(".myclass");

jQuery - change table cells position

how can I change via jquery the cells position from 1 2 to 2 1 ?
<table id='mytable'>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
$('#mytable tr td:eq(0)').appendTo('#mytable tr');
The JSFIDDLE.
If you want to change all the second td to first position in your table, then you can use:
$.each($('#mytable tr td:eq(1)'), function() {
$(this).insertBefore($(this).prev());
})
Actually, above code will not work if your table have more than one <tr> element, if that is the case then you need to use .find():
$('#mytable tr').find('td:eq(1)').each(function() {
$(this).insertBefore($(this).prev());
});
Fiddle Demo
References: .each() , .find() , .insertBefore() , .prev()
with append
http://jsfiddle.net/F7HmQ/1/
$(function(){
var td = $("td").first() ;
$("tr").first().append(td);
});

jQuery .on() event not working with :lt() selector

I am trying to generate click event on every table data <TD> except the last one <td> but It's just working with the First row not the rest.
HTML:
<table class="table" style="width:100%;">
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
JS code:
$('.table tbody').on('click', 'tr td:lt(3)', function(){
// Trying to check the click event
console.log('working');
});
JSFIDDLE
jsfiddle
If i remove the :lt(3) selector then its working fine but i don't know why it's not working with less then selector?
Well, this is how the :lt() selector works:
The index-related selectors (including this "less than" selector)
filter the set of elements that have matched the expressions that
precede them. They narrow the set down based on the order of the
elements within this matched set. For example, if elements are first
selected with a class selector (.myclass) and four elements are
returned, these elements are given indices 0 through 3 for the
purposes of these selectors.
In your case, tr td is matched first which matches 16 cells, then the first 3 elements from the resulting set are filtered. You could revise the code like this:
// trap clicks on .table tbody and filter all td elements
$('.table tbody').on('click', 'td', function () {
if ($(this).index() < 3) {
console.log('working');
}
});
Or better, use the CSS3 :nth-child() selector which is also available in jQuery:
// trap clicks on .table tbody and filter all td elements
// that are "-n+3"th child of their parent
$('.table tbody').on('click', 'td:nth-child(-n+3)', function () {
console.log('working');
});
The nth-child selector is explained here.
You can also do
$('.table tbody tr').on('click', 'td:lt(3)', function(){
console.log('working');
});
If you don't, it will take the first 3 td, of all tbody, not the one of each row (you can try your code with 5 instead of 3, and see what's happening : it will be applied on tr 1 : td 1, td 2, td 3, td 4 and tr2 : td 1 ( the first 5 td of tbody)
jsfiddle

How to set the row id [ TR ] and column id [ TD] in displaytag?

I am using Displaytag to display the DataGrid. Now, I have to change the color of rows based on some calculation. Like if
the value of column3 + column4 > coulmn5 then the row color should be yellow
value of column3 + column4 < coulmn5 then the row color should be red
value of column3 + column4 = coulmn5 then the row color should be white
I think the only way to do this is by using getElementByID() method
Note: i don't want to consider the solution using getElementsByTagName()[index] , reason being later on the column ordering might change.
at present i am using the following code, which i want to change.
var rows = tbody.getElementsByTagName("tr");
Iterate the rows Object
var tdObj = rows[i].getElementsByTagName("td")[3]
First, I do not believe it is possible to set the ids on the td's or tr's in displaytag without modifying the source. This has not left my list of things to do, but for now I have a work around for you.
Instead of defining your table:
<display:table id='row' name="..." export="true" requestURI="">
<display:column property="usefulData" title="Useful data" sortable="true" />
... more columns ...
</display:table>
do this:
<display:table id='row' name="..." export="true" requestURI="">
<display:column title="Useful data" sortable="true" >
<span id='${row.usefulData}' class='css_class_selector'>${row.usefulData}</span>
</display:column>
</display:table>
Note the span wrapping the printed data. Now you can select the data relating printing inside your table, which is probably what you want; to select your data, as opposed to specifically selecting the td's and tr's.
An id would be one way to do it. Another would be setting a class on each td (so you can re-use the same class on each row). Then you'd iterate over the cells looking for the one with the right className. You can abstract this away into a getElementsByClassName function if you like.
A way to do it with less markup would be to keep a column-to-index lookup and use that to get the column number instead of iterating over cells on every row. You could get this information from classes on the header, or col elements. eg.:
<script type="text/javascript">
function check(table) {
// Work out which column is at which index
//
var columns= {};
var ths= table.tHead.rows[0].cells;
for (var i= ths.length; i-->0;)
if (ths[i].className.indexOf('column-')==0)
columns[ths[i].className.substring(7)]= i;
// Check each row
//
var rows= table.tBodies[0].rows;
for (var i= rows.length; i-->0;) {
var cells= rows[i].cells;
var a= +cells[columns.a].innerHTML;
var b= +cells[columns.b].innerHTML;
var sum= +cells[columns.sum].innerHTML;
var right= a+b==sum;
rows[i].className= right? 'right' : 'wrong';
}
}
</script>
<style>
.right { background: green; }
.wrong { background: red; }
</style>
<table id="t">
<thead>
<tr>
<th class="column-a">A</th>
<th class="column-b">B</th>
<th class="column-sum">Sum</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
<button onclick="check(document.getElementById('t'));">Check</button>
Note using innerHTML to get the text content is a bit naughty, but it works OK for numbers as they cannot contain HTML special characters. For arbitrary text you would need an extract-text-content function.
Using rows/cells is preferable to getElementsByTagName. It's quicker, easier-to-read and you don't have to worry about nested tables.

Categories

Resources