I have table which looks like this jsfiddle
Now i need to implement functionality to print just selected rows. Rows can be selected by clicking on check-box on the right of each row.
Can somebody advise me how to complete it, please?
I already implemented full table printing functionality with
var divToPrint=document.getElementById("pretazna");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
Try this code... it doesn't create a popup window but instead hides rows using a print stylesheet (demo)
CSS
#media print {
#print, tfoot, tbody tr:not(.printme) {
display: none !important;
}
}
Javascript
function matches(el, selector) {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
var matches = document.querySelectorAll(selector),
i = matches.length;
while (--i >= 0 && matches.item(i) !== el) {}
return i > -1;
}
function closest(el, selector) {
while (el && !matches(el, selector)) {
el = el.parentNode;
}
return matches(el, selector) ? el : null;
}
document.querySelector('table').addEventListener('change', function(event) {
var target = event.target;
closest(target, 'tr').classList[target.checked ? 'add' : 'remove']('printme');
})
document.querySelector("#print").addEventListener('click', function() {
window.print();
});
Related
I have a table on my page, and a filtering text box above it that works fantastic, using the following JQuery:
$("#searchInputCompanies").keyup(function () {
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#cBody").find("tr");
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function(i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.text().toLowerCase().indexOf(data[d].toLowerCase()) > -1) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
$('#selectAllCompanies').prop('checked', '');
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});
How can I set up a Reset Filter button for this?
Uhh, this is quite a bad implementation :(
First, you need to change the event for $("#searchInputCompanies") to make it all a bit easier. So, it will become $("#searchInputCompanies").on("input", function() {...
$("#resetAction").on("whatEventYouWant", function() {
$("#searchInputCompanies").val("").trigger("input");
});
This will trigger input event on $("#searchInputCompanies") and because the text box is empty all rows will become visible.
Fiddle
$(document).live('mouseup', function () {
flag = false;
});
var colIndex;
var lastRow;
$(document).on('mousedown', '.csstablelisttd', function (e) {
//This line gets the index of the first clicked row.
lastRow = $(this).closest("tr")[0].rowIndex;
var rowIndex = $(this).closest("tr").index();
colIndex = $(e.target).closest('td').index();
$(".csstdhighlight").removeClass("csstdhighlight");
if (colIndex == 0 || colIndex == 1) //)0 FOR FULL TIME CELL AND 1 FOR TIME SLOT CELL.
return;
if ($('#contentPlaceHolderMain_tableAppointment tr').eq(rowIndex).find('td').eq(colIndex).hasClass('csstdred') == false) {
$('#contentPlaceHolderMain_tableAppointment tr').eq(rowIndex).find('td').eq(colIndex).addClass('csstdhighlight');
flag = true;
return false;
}
});
i am Dragging on table cells.
While dragging(move downward direction) i have to move table scroll also.
and also i want to select cells reverse (upward direction).
what should i do.
I have make an selection on tr class.
Updated jsFiddle: http://jsfiddle.net/qvxBb/2/
Disable normal selection like this:
.myselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;
}
And handle the row-selection with javascript like this:
// wether or not we are selecting
var selecting = false;
// the element we want to make selectable
var selectable = '.myselect tr:not(:nth-child(1)) td:nth-child(3)';
$(selectable).mousedown(function () {
selecting = true;
}).mouseenter(function () {
if (selecting) {
$(this).addClass('csstdhighlight');
fillGaps();
}
});
$(window).mouseup(function () {
selecting = false;
}).click(function () {
$(selectable).removeClass('csstdhighlight');
});
// If you select too fast, js doesn't fire mousenter on all cells.
// So we fill the missing ones by hand
function fillGaps() {
min = $('td.csstdhighlight:first').parent().index();
max = $('td.csstdhighlight:last').parent().index();
$('.myselect tr:lt('+max+'):gt('+min+') td:nth-child(3)').addClass('csstdhighlight');
}
I just added a class in the HTML. All the HTML and CSS in unchanged besides what I've shown here.
Updated jsFiddle: http://jsfiddle.net/qvxBb/2/
There are several problems with your table, but I will correct the one you asked for.
To make your table scroll when your mouse get outside the container, add this code inside your mousedown event handler :
$('body').on('mousemove', function(e){
div = $('#divScroll');
if(e.pageY > div.height() && (e.pageY - div.height()) > div.scrollTop()) {
div.scrollTop(e.pageY - div.height());
}
});
and this, inside your mouseup event handler :
$('body').off('mousemove');
See the updated Fiddle
But now, another issue appear. This is because of the rest of your code. The lines are not selected because the mouse leave the column.
Try removing the return false; inside
$('#contentPlaceHolderMain_tableAppointment tr').eq(rowIndex).find('td').eq(colIndex).addClass('csstdhighlight');
flag = true;
return false; //Remove this line
}
Because return false; stops browser default behavior (scrolling automatically).
DEMO
I am trying to write a script that detects if a tables tds are empty and if they are hide the parent tr
I've searched Stack Overflow and found other scripts but none seem to work for me.
So far I have:
$(".table tr").each(function() {
var cell = $(this).find('td').html();
if (cell == null){
console.log('empty');
$(this).parent().addClass('nodisplay');
}
});
but just can't get it working. Any advice would be appreciated!
Fiddle: http://jsfiddle.net/MeltingDog/S8CUa/1/
Try this -
$("table tr td").each(function() {
var cell = $(this);
if ($(cell).text().length == 0){
console.log('empty');
$(this).parent().addClass('nodisplay');
}
});
Demo
you should try this.
jQuery(document).ready(function(e) {
jQuery(jQuery('table tr td:empty').parents('tr')).addClass('nodisplay');
});
.html() only returns the content of the first matched element, so if your rows have more than one cell this wouldn't work. .text() might be a better fix, unless you have images or other empty tags in the cells.
$("table tr").each(function() {
var cell = $.trim($(this).find('td').text());
if (cell.length == 0){
console.log('empty');
$(this).addClass('nodisplay');
}
});
DEMO
It seems you want to hide rows that have only whitespace content (but the cells might have other element child nodes). Using plain javascript:
var rows = document.getElementsByTagName('tr');
var i = rows.length;
while (i--) {
if ( !trim(getText(rows[i])) ) {
rows[i].className += ' nodisplay';
}
}
Helpers:
function trim(s) {
return s.replace(/(^\s*)|(\s*$)/g, '');
}
function getText(el) {
if (typeof el.textContent == 'string') {
return el.textContent;
} else if (typeof el.innerText == 'string') {
return el.innerText;
}
}
$('table tr').each(function(){
var hide = true;
$('td',this).each(function(){
if ($.trim($(this).text()) != "")
hide = false;
});
if(hide)
$(this).closest('tr').hide();
// OR $(this).closest('tr).addClass('nodisplay');
});
Hide table, if table have no rows using jquery
$('.tblClass').each(function(){
if($(this).find('.rows').length == 0){
$(this).hide();
}
});
Here are 4 functions I use to improve the usability of a table by:
If cell contains a checkbox and you click outside of a checkbox
The the tr contains data-url then the whole row is "clickable"
with CSS hover effect and redirects on click.
If the last column in the table contains a relative/absolute URL
then also redirects on click.
Check all checkboxes.
Here's my code:
// Click table cell auto check checkbox
$('table tr td').has("input[type=checkbox]").click(function(event) {
// Onl call this if click outside of the checkbox itself
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
// Table row click
$('table tr[data-url]').each(function(){
var url = $(this).attr("data-url");
if(url.length){
$(this)
.addClass("clickable")
.find("td").click(function(){
window.location = url;
return false;
});
}
});
// Double click row, open edit link
$('table:not(.noDoubleClick) tr td').dblclick(function(e) {
var linkEl = $(this).parents('tr').find('td:last-child a');
var linkElHref = linkEl.attr('href');
// Check if has href and http protocol
if(!linkElHref.length || linkEl.prop('protocol').indexOf("http") !== 0){
e.preventDefault();
return false;
}
if (linkElHref && linkEl.attr('onclick') === undefined && !linkEl.hasClass("popme")) {
document.location = linkElHref;
} else {
linkEl.click();
}
});
// Check all checkboxes
$('table input[type=checkbox][name^="checkall"]').live("click",function() {
var parent = $(this).parents('table');
if(!$(this).parents('table').length){
parent = $(this).parents("form");
}
parent.find(':checkbox[name^="' + $(this).attr("data-name") + '"]').prop("checked", this.checked);
});
Q: how can I modify this into one function so that jquery only has to search for tables once?
Example jsfiddle
Thanks for every bodies suggestions I have ended up taking a slightly different approach:
$('table').each(function(){
var $table= $(this), $cell, $row;
// TABLE ROWS
$table.find('tr').each(function(){
$row = $(this);
// Row click redirect to data-url
var url = $row.attr("data-url");
if(url && url.length){
$row.addClass("clickable").find("td").click(function(){
window.location = url;
return false;
});
}
// TABLE HEADING CELLS
$row.find('th, thead td').each(function(){
$cell = $(this);
// Check all checkboxes
$cell.find('input.checkall').live("click",function() {
var parent = $(this).parents('table');
if(!$(this).parents('table').length){
parent = $(this).parents("form");
}
parent.find(':checkbox[name^="' + $(this).attr("data-name") + '"]').prop("checked", this.checked);
});
});
// TABLE CELLS
$row.find('td').each(function(){
$cell = $(this);
// Check checbox onClick
if($cell.find("input[type=checkbox]")){
$cell.click(function(e) {
if(e.target.type !== 'checkbox') $(':checkbox', this).trigger('click');
});
}
// Double click open edit link
if(!$table.hasClass("noDoubleClick")){
$cell.dblclick(function(e){
var linkEl = $(this).parents('tr').find('td:last-child a');
var linkElHref = linkEl.attr('href');
// Check if has href and http protocol
if(linkElHref && (!linkElHref.length || linkEl.prop('protocol').indexOf("http") !== 0)){
e.preventDefault();
return false;
}
if (linkElHref && linkEl.attr('onclick') === undefined && !linkEl.hasClass("popme")) {
document.location = linkElHref;
} else {
linkEl.click();
}
});
}
}); // end CELLS
}); // end ROWS
}); // end TABLE
You should use .on , .live is being deprecated:
$(document).on('click', 'table tr td', function(event)
{
if( $(this).has("input[type=checkbox]"))
{
if (event.target.type !== 'checkbox')
$(':checkbox', this).trigger('click');
}
});
// Table row click
$(document).on('click', 'table tr[data-url] td', function(e)
{
var url = $(this).parent().attr("data-url");
if(url.length)
{
window.location = url;
return false;
}
});
$(document).on('dblclick', 'table:not(.noDoubleClick) tr td', function(e) {
debugger;
var linkEl = $(this).parents('tr').find('td:last-child a');
var linkElHref = linkEl.attr('href');
// Check if has href and http protocol
if(!linkElHref.length || linkEl.prop('protocol').indexOf("http") !== 0){
e.preventDefault();
return false;
}
if (linkElHref && linkEl.attr('onclick') === undefined && !linkEl.hasClass("popme")) {
document.location = linkElHref;
} else {
linkEl.click();
}
});
// Check all checkboxes
$(document).on('click', 'table input.checkall', function() {
var parent = $(this).parents('table');
if(!$(this).parents('table').length){
parent = $(this).parents("form");
}
parent.find(':checkbox[name^="' + $(this).attr("data-name") + '"]').prop("checked", this.checked);
});
I have made the basic stubs here, i dont want to rewrite all your code.
$(document).ready(function(){
$('table').each(function(){
var table = $(this);
table.find('tr').each(function (){
var tr = $(this);
tr.find('td').each(function(){
var td = $(this);
td.has("input[type=checkbox]").click(function(event) {
// Only call this if click outside of the checkbox itself
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
});
});
});
The logic is: Find all tables, loop through all the tr's and then the td's. I've did your first function and hope that explains how it could be used?
The best thing to do in this case is to:
Get all of the tables in the page
Loop through each table
Find and apply logic to the individual elements as needed
$('table').each(function(){
var table = $(this),
rows = table.find('tr[data-url]'),
cells = table.find('td'),
all = table.find('input[type=checkbox][name^="checkall"]'),
edit = table.is('.noDoubleClick');
cells.each(function(){
//Apply your logic here
if(edit === true){
//Apply your logic to this cell here
}
});
rows.each(function(){
//Apply your logic to this row here
});
all.on('click',function(){
//Apply your logic here
});
});
There's this div in a site:
<div class="section1">
....
</div>
I want to remove it using a Chrome extension... Can someone give only the javascript code alone? Thanks.
function removeElementsByClassName(names) {
var els = document.getElementsByClassName(names),
i, element;
for (i = els.count - 1; i > 0; i -= 1) {
element = els[i];
element.parentElement.removeChild(element);
}
}
removeElementsByClassName('section1');
function removeElement(parentDiv, childDiv){
if (childDiv == parentDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
removeElement('parent','child');
If by removing you simply mean hiding then you can run this from a content script:
document.querySelector('div.section1').style.display = 'none';
(this assumes there is only 1 section1 element on the page, otherwise you would need to use document.querySelectorAll and filter the results based on some criteria)