dynamic tooltip text on every cell of table - javascript

i can set tool-tip for each cell of my table using title
but is there a way to make the tool-tip text to be dynamic ?
for example when i hover on any cell of table it show information about that cells entire row.
<td title="something">46879</td>
example using datatables plugin :
$(document).ready(function() {
$('#example tbody tr').each( function() {
var sTitle;
var nTds = $('td', this);
var sBrowser = $(nTds[1]).text();
var sGrade = $(nTds[4]).text();
if ( sGrade == "A" )
sTitle = sBrowser+' will provide a first class (A) level of CSS
support.';
else if ( sGrade == "C" )
sTitle = sBrowser+' will provide a core (C) level of CSS support.';
else if ( sGrade == "X" )
sTitle = sBrowser+' does not provide CSS support or has a broken
implementation. Block CSS.';
else
sTitle = sBrowser+' will provide an undefined level of CSS
support.';
this.setAttribute( 'title', sTitle );
} );
var oTable = $('#example').dataTable();
$( oTable.fnGetNodes() ).tooltip( {
"delay": 0,
"track": true,
"fade": 250
} );
} );
this is what i mean :
https://jsfiddle.net/pow7651t/1/

Please have a look at following solution. Note that, I have added an extra variable for columns. Let me know if this works, or if there is any issue with this solution.
$(document).ready(function() {
var columns = ['Names', 'Reg Number', 'ID Code']
$('#example tbody tr').each(function() {
var cells = $('td', this);
var titleArr = cells.map(function(index) {
return columns[index] + '=' + this.innerHTML;
});
cells.each(function(index) {
var finalTooltip = titleArr.filter(function(i){
return index !== i;
});
$(this).attr('title', finalTooltip.toArray().join(','))
})
var name = cells[0];
var regNumber = cells[1];
var idCode = cells[2];
});
var oTable = $('#example').dataTable();
$(oTable.fnGetNodes()).tooltip({
"delay": 0,
"track": true,
"fade": 250
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="example">
<thead>
<th>Names</th>
<th>RegNumber</th>
<th>ID Code</th>
</thead>
<tbody>
<tr>
<td>Ryan</td>
<td>49765</td>
<td>34</td>
</tr>
<tr>
<td>John</td>
<td>58964</td>
<td>42</td>
</tr>
<tr>
<td>Daniel</td>
<td>472658</td>
<td>24</td>
</tr>
</tbody>
</table>

You have to create a title attr for each cell of your table ,
in the below Fiddle a did loop throw each row , and inside those a get the text and the header of each cell except the current cell (.not(this)) and then set the title attribute to this last .
See this Fiddle

Related

Toggle and Filter JavaScript function - combine

I have two JavaScript functions: one toggles (hide/show) a table row when a link is clicked, and another that filters table rows (showing only rows with text that's entered into a text field). When someone enters text into the text field, I want to be able to hide all of the shown table rows (that were toggled). So, basically, I'm trying to add part of the toggle function to the filter function. The toggle function needs to function on its own, but all items will be hidden when text is entered.
Toggle Function
If a table row has an ID (id="celltohid1" or id="celltohid1"), then the following function hides or shows that row when a link it clicked...
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'table-row')
e.style.display = 'none';
else
e.style.display = 'table-row';
}
//-->
</script>
Filter Function
Below is the Filter function...
<script>
$(document).ready(function(){
$(".search").on("keyup",function(){
var searchTerm = $(this).val().toLowerCase();
$("#DMTbl tbody tr.contentrow").each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
});
});
});
</script>
Goal (and my weak attempt)
I need to add functionality that hides all the rows with IDs that contain "celltohid" (if all the id's are celltohid#)... I don't know JavaScript, so below is my weak attempt at this. Every row with the unique ids "celltohid#" has a class "descexpand". So, I tried adding a toggle to change the display style for that class ... but it's not working...
<script>
$(document).ready(function(){
$(".search").on("keyup",function(){
var searchTerm = $(this).val().toLowerCase();
$("#DMTbl tbody tr.contentrow").each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
var clasname = "descexpand";
var e = document.getElementByClass(clasnam);
if(e.style.display == "table-row") {
e.style.display = "none";
}
});
});
});
</script>
Can anyone help?
You don't need <td/> id's for filtering. You can simply check the string in <tr/> and hide if there text doesn't exist.
$(document).ready(function() {
$(".search").off('keyup').on("keyup", function() {
var searchTerm = $(this).val().toLowerCase();
$("table tbody tr").each(function(index) {
var lineStr = $(this).text().toLowerCase();
if (lineStr.indexOf(searchTerm) < 0) {
$(this).hide();
} else {
$(this).show();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table> 
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>    
<th>Age</th>
</tr>
</thead> 
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>    
<td>50</td> 
</tr> 
<tr>   
<td>Eve</td>
<td>Jackson</td>    
<td>94</td> 
</tr>
</tbody>
</table>
<input class="search" type="text" />

jQuery DataTables filter rows based on multiple values

I am trying to have multiple filters that will hide/show rows on my datatable based on which filters are selected. My plan is to place the filter values in an array and compare those to the data-search attribute in the first column, but what I currently have does not work.
Here's a JSfiddle that I have plus code below
https://jsfiddle.net/dmcgrew/06j4pxjk/3/
HTML with checkboxes for filters and the table data..
<label>
<input type="checkbox" name="cat" value="cat" class="filter"> Cats
</label>
<label>
<input type="checkbox" name="dog" value="dog" class="filter"> Dogs
</label>
<table class="select_items">
<thead>
<tr>
<th>Item</th>
<th>Description</th>
<th>Crest Allowed</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td data-search="cat">1</td>
<td>Testing Bowl</td>
<td>NO</td>
<td><button class="button">Select</button></td>
</tr>
<tr>
<td data-search="dog">32</td>
<td>Cup Test</td>
<td>NO</td>
<td><button class="button">Select</button></td>
</tr>
<tr>
<td data-search="dog">3335</td>
<td>Bowl Test</td>
<td>NO</td>
<td><button class="button">Select</button></td>
</tr>
</tbody>
</table>
The JS..
var select_items = $('.select_items').DataTable();
var filters = [];
$('input.filter').on('change', function(){
var filters = [];
$("input.filter:checked").each(function(){
var checkedBox = $(this).val();
if (filters.indexOf(checkedBox) === -1){
filters.push(checkedBox);
}
});
console.log(filters);
if(this.checked){
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex){
return (data[0].indexOf(filters) > -1) ? true : false;
}
);
}
select_items.draw();
if(this.checked){
$.fn.dataTable.ext.search.pop();
}
});
Considering, accepted answer refers to legacy interface fnFilter and, as of DataTables 1.10 new API is suggested, I'll allow myself to provide more up to date solution, which is, in my opinion, way more scalable, neat and simple:
//define statical data
var srcData = [
{search: 'Cat', item: '1', descr: 'Testing Bowl', crest: 'NO'},
{search: 'Dog', item: '32', descr: 'Cup Test', crest: 'NO'},
{search: 'Dog', item: '3335', descr: 'Bowl Test', crest: 'NO'},
];
//define dataTable object
var dataTable = $('#mytable').DataTable({
sDom: 't',
data: srcData,
columns: [
{title: 'Item', data: 'item'},
{title: 'Description', data: 'descr'},
{title: 'Crest Allowed', data: 'crest'},
]
});
//put in place dynamically created checkboxes
var searchValues = [];
dataTable.data().sort().toArray().forEach(row => {
if(searchValues.indexOf(row.search)==-1) searchValues.push(row.search);
});
var checkboxes = searchValues.reduce((html, item) => html += `<input type="checkbox" value="${item}" class="filter">${item}</input>`,'');
$(checkboxes).insertBefore($('#mytable'));
//employ $.fn.DataTable.ext.search
var lookupValues = [];
$.fn.DataTable.ext.search.push((settings, row, index, rowObj) => lookupValues.indexOf(rowObj.search) > -1 || lookupValues.length == 0);
//watch checkboxes and redraw table on change accordingly
$(".filter").on('change', () => {
lookupValues = [...$('.filter:checked')].map(checkbox => $(checkbox).val());
dataTable.draw();
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>
I made a few changes in your code, using the fnFilter API:
Documentation: https://datatables.net/docs/DataTables/1.9.0/DataTable.html#fnFilter
$(function() {
otable = $('.select_items').dataTable();
})
function filterme() {
//build a regex filter string with an or(|) condition
var types = $('input:checkbox[name="filter"]:checked').map(function() {
return '^' + this.value + '\$';
}).get().join('|');
//filter in column 0, with an regex, no smart filtering, no inputbox,not case sensitive
otable.fnFilter(types, 0, true, false, false, false);
}
You can see it working here: JSFiddle demo
You have to check for the filter length.
If there is no filter, the $.fn.dataTable.ext.search.push function has to return true for ALL rows.
And, I think that search.pop() should apply on uncheck too...
var select_items = $('.select_items').DataTable();
$('input.filter').on('change', function(){
var filters = [];
$("input.filter:checked").each(function(){
var checkedBox = $(this).val();
if (filters.indexOf(checkedBox) === -1){
filters.push(checkedBox);
}
});
console.log(filters.length);
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex){
if(filters.length>0){
return (data[0].indexOf(filters) > -1) ? true : false;
}else{
return true;
}
});
select_items.draw();
$.fn.dataTable.ext.search.pop();
});
Updated Fiddle

jQuery - get next element inside checkbox each

I have a table with following columns: checkbox, text, text, ...
For every selected checkbox I need to get the 2nd text value and test if contains some value.
My code so far
$('input:checkbox').each(function () {
var current = $(this);
if (current.is(':checked')) {
var txt = current.next('.inf-name').text();
if (txt.contains(inf) { ... }
}
});
razor code:
<table class="table table-bordered table-modified">
<thead>
<tr>
<th></th>
<th>State</th>
<th>Lookup Type</th>
<th>Plates</th>
<th>Notices</th>
</tr>
</thead>
<tbody>
#Html.HiddenFor(p => p.OrgUnitID, new { #Value = orgUnitId })
#for(var ind = 0; ind < records.Count(); ++ind)
{
var r = records[ind];
var i = ind;
#Html.HiddenFor(p => p.Comp[i].State, new { #Value = #r.State })
<tr>
<td>#Html.CheckBoxFor(p => p.Comp[i].Checked)</td>
<td>#r.State</td>
#if (dict.ContainsKey(r.State))
{ <td class="inf-name">#dict[r.State].ToString()</td> }
else
{ <td class="inf-name"></td> }
<td>#Html.ActionLink(#r.Plates.ToString(CultureInfo.InvariantCulture), "Plates", new { controller = "Lookup", state = #r.State})</td>
<td>#Html.ActionLink(#r.Notices.ToString(CultureInfo.InvariantCulture), "Plates", new { controller = "Lookup" }, new { state = #r.State })</td>
</tr>
}
</tbody>
</table>
where inf-name is the class on 2nd element. I can't get it done. Anyone know a solution?
using next() will get the direct sibling , you need to get parent for check box which is a <td> find the next next sibling using nextAll().eq(1) , get the text inside the that sibling using .text()
Edit :
if you want your target using classes ( provided classes will never change later ) , then just change your code to be :
$('input:checkbox').each(function () {
var current = $(this);
if (current.is(':checked')) {
var txt = current.next('.inf-name').eq(1).text();
if (txt.contains(inf) { ... }
}
});
var currentRows = $('.table tbody tr');
$.each(currentRows, function () {
$(this).find(':checkbox').each(function () {
if ($(this).is(':checked')) {
console.log($(currentRows).eq(1).val());
}
});
});

Using Jquery and $(this).text() to replace th text

I'm trying append a two digit year to a column header that is autogenerated for me. It seems like a simple problem. I have this table
<table border="1" id="Datatable1">
<tr>
<th>Jan-</th>
<th>Feb-</th>
</tr>
<tr>
<td>January's data</td>
<td>February's data</td>
</tr>
</table>
and this jquery
$(document).ready(
function () {
var TwoDigitYear = '14';
$('#DataTable1 th').each(function () {
var curtext = $(this).text();
if (curtext != "") {
var newtext = curtext + TwoDigitYear;
$(this).text(newtext);
}
});
}
);
For some reason, I can see the value changed if I put a console.log in the code, but the web page doesn't change.
Here's a jsfiddle: http://jsfiddle.net/PasadenaJacket/Ztnvr/#base
Instead of DataTable1 you need to do Datatable1 then it should work.
See UPDATED FIDDLE HERE

JQuery, Find results in table column

Im trying to find the results in a table column if its set in my function below, most of this was setup by someone else, ive just added some extras into it, my final one is searching 1 column only by name set in the thead but alas in its current edition nothing happens at all :|
thanks for any help
USAGE
<a href='javascript:searchTable("Bob", "table",1,"Name");'>Test</a>
TABLE
<table id="table" class="table">
<thead>
<tr>
<th id="blank"> </th>
<th id="Name">Name</th>
<th id="Dept">Department</th>
<th id="JobTitle">Job Title</th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td>Bob</td>
<td>IT</td>
<td>IT Support</td>
</tr>
<tr>
<td> </td>
<td>Fred</td>
<td>Finance</td>
<td>Finance Man</td>
</tr>
</tbody>
</table
FUNCTION
function searchTable(inputVal, tablename,starts, column) {
var table = $(tablename);
table.find('tr:not(.header)').each(function (index, row) {
if (column != '') {
//Columnname
var Cells = $(row).find('td').eq(column);
} else {
//AllCells
var Cells = $(row).find('td');
}
if (Cells.length > 0) {
var found = false;
Cells.each(function (index, td) {
if (starts == 1) {
var regExp = new RegExp((starts ? '^' : '') + inputVal, 'i');
} else {
var regExp = new RegExp(inputVal, 'i');
}
if (regExp.test($(td).text())) {
found = true;
return false;
}
});
if (found == true) $(row).show().removeClass('exclude'); else
$(row).hide().addClass('exclude');
}
});
}
As you're passing the column as a string, you need get the corresponding elements index:
var Cells = $(row).find('td:eq(' + $('#' + column).index() + ')');
The above presumes that you're matching based on the id, if you're matching based on the text within the <th> you could use the :contains selector:
$(row).find('td:eq(' + $(table.prop('id') + ' th:contains(' + column + ')').index() + ')');
If you can control and modify the function calls, the best thing to do would be to just pass the elements index directly to the function:
javascript:searchTable("Bob", "table", 1, 1); <-- Would be the "Name" column
That way, you won't have to do any of the above.
By the way, your table selector is incorrect based on your comment, not sure if that's just a typo on your part?
var table = $(tablename);
Should be:
var table = $('#' + tablename);
I am not sure what you are trying to control but you can use this to loop through rows and get the values of cells.
$("#table>tbody>tr").each(function(){
var name= $(this).children("td").eq(1).html();//Name
var department= $(this).children("td").eq(2).html();//Department
var jobTitle= $(this).children("td").eq(2).html();//Job Title
alert(name);
});
http://jsbin.com/uvefud/1/edit
Edit:
You can try this searchTable function.
function searchTable(name,tableName,row,column){
var $Tds= $("#"+tableName+">tbody>tr").eq(row-1).children("td");
if(column=="Name"){
$Tds.eq(1).html(name);
}
else if(column=="Dept"){
$Tds.eq(2).html(name);
}
else if(column=="JobTitle"){
$Tds.eq(3).html(name);
}
}
http://jsfiddle.net/W9zpq/2/
Usage: This will update the name column of 2nd row of tbody to 'Bob'
searchTable("Bob", "table",2,"Name")

Categories

Resources