I have this javascript code to print html table from a PHP document.
function printReport()
{
var data = '<input type="button" value="Print this page" onClick="window.print()">';
data += '<input type="button" value="Close this page" onClick="window.close()">';
data += '<table border="0"';
data += $('#reportTable').html();
data += '</table>';
myWindow=window.open('','','scrollbars=yes,resizable=yes,width=500,height=400');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.write(data);
myWindow.focus();
};
It opens the new windows, displays the content right, the close button works fine, however the print button doesnt work.
My printer is working properly, I printed from word or any other app and works fine.
My problem is: the print function window.print() is NOT working.
If anyone could give me a hand, would be appreciated.
Cheers
Change:
data += '<table border="0"';
to
data += '<table border="0">';
and tell us the net result. Tested with simple HTML content within the table. Assuming your .html() call returns valid table data, the window should be printable now.
Working fiddle here: http://jsfiddle.net/aV85r/
Related
document.getElementById("outputDiv").innerHTML = "";
document.getElementById("outputDiv").innerHTML += "<table border=1 width=100%><tr>";
for(j=1;j<=10;j++)
{
document.getElementById("outputDiv").innerHTML += "<td align=center>"+String.fromCharCode(j+64)+"</td>";
}
document.getElementById("outputDiv").innerHTML += "</tr></table>";
I want to draw a table using Javascript.
So I wrote the code like above.
I think it draw one row that has 10 columns, but it doesn't work.
Anyone know about this problem???
I ran into this problem years ago, too.
The problem is that when you use the innerHTML property to add HTML, after each update, the underlying engine will close unclosed tag (and fix other bad HTML) for you. So after the second line, the <table> and <tr> tags are automatically closed and all content after that will just be written outside the table.
Method 1
(The easy way)
Use a string to store the HTML for the whole table and update it all at once.
var HTML = "<table border=1 width=100%><tr>";
for(j=1;j<=10;j++)
{
HTML += "<td align=center>"+String.fromCharCode(j+64)+"</td>";
}
HTML += "</tr></table>";
document.getElementById("outputDiv").innerHTML = HTML;
Fiddle
Method 2
(The better way)
Use DOM functions
var table = document.createElement('table');
table.setAttribute('border','1');
table.setAttribute('width','100%')
var row = table.insertRow(0);
for(j=1; j<=10; j++){
var text = document.createTextNode(String.fromCharCode(j+64));
var cell = row.insertCell(j-1);
cell.setAttribute('align','center')
cell.appendChild(text);
}
document.getElementById("outputDiv").appendChild(table);
Fiddle
Method 2 enhanced
(The yet better way)
Use CSS instead of HTML attributes. The latter is generally depreciated as of latest specs.
A great resource to start learning CSS is the Mozilla Developer Network
Fiddle
Method 3
(The long way, but the best in the long-run)
Use jQuery.
$('<table>').append('<tr>').appendTo('#outputDiv');
for(j=1; j<=10; j++)
$('<td>').text(String.fromCharCode(j+64)).appendTo('tr');
Fiddle
I think the main problem is that your attributes are not quoted.
But it's almost always a bad idea to repeatedly update the content of a dom element in a loop—each time you update dom content it causes some internal work to be done by the browser to make sure the page layout is current.
I would build the html string up locally, then make one final update when done. (and of course make sure your attributes are quoted)
document.getElementById("outputDiv").innerHTML = "";
var newTable = "<table border='1' width='100%'><tr>";
for(j = 1; j <= 10; j++) { //opening braces should always be on the same line in JS
newTable += "<td align='center'>" + String.fromCharCode(j+64) + "</td>";
}
newTable += "</tr></table>";
document.getElementById("outputDiv").innerHTML = newTable;
So this is a weird one as every topic I've found on the subject has the exact opposite of my problem.
I'm using some JavaScript in SharePoint Online to replace the innerHTML of some elements, but whenever the function runs it is appending content rather than overwriting it.
I've tried the JS method of setting the innerHTML to something else first, then to the value (no luck), and also moving it to a jQuery call to set it. In both cases it does the same thing. Same problem observed on both Edge and Chrome.
Code is below - any ideas? (Have not included the whole script, just the specific function as it's quite a big script and the other bits are working as expected).
function getThisCompany() {
thisCompanyEnum = thisCompany.getEnumerator();
while (thisCompanyEnum.moveNext()) {
var currentCompany = thisCompanyEnum.get_current();
var thisCompanyId = currentCompany.get_item('ID');
var thisCompanyName = currentCompany.get_item('companyName');
var thisCompanyPhone = currentCompany.get_item('companyPhone');
var thisCompanyUrl = currentCompany.get_item('companyUrl');
var thisCompanyLogo = currentCompany.get_item('companyLogo');
// Check for a null value - if it is null console throws an error and stops the script, so load a default logo
if (thisCompanyLogo == null) {
thisCompanyLogo = "https://consiliumuk.sharepoint.com/POC/minicrm/CRM%20Images/nologo.png";
}
else {
thisCompanyLogo = thisCompanyLogo.get_url();
}
var thisCompanyAddress = currentCompany.get_item('companyAddress');
var thisCompanyMarkupBlock = "<table><tr><td colspan=2><b>";
thisCompanyMarkupBlock += thisCompanyName;
thisCompanyMarkupBlock += "</b></td></tr><tr><td colspan=1 valign=top><img height=100 width=100 src='";
thisCompanyMarkupBlock += thisCompanyLogo;
thisCompanyMarkupBlock += "' /></td><td colspan=1 valign=top>";
thisCompanyMarkupBlock += thisCompanyAddress;
thisCompanyMarkupBlock += "<p /><i>";
thisCompanyMarkupBlock += thisCompanyPhone;
thisCompanyMarkupBlock += "</i><br /><a href=";
thisCompanyMarkupBlock += thisCompanyUrl;
thisCompanyMarkupBlock += ">Visit company website</a></td></tr></table><p /><input id='loadExtended' type='button' value='Load' onClick='loadExtendedDetails(";
thisCompanyMarkupBlock += thisCompanyId;
thisCompanyMarkupBlock += ");' />";
alert(thisCompanyMarkupBlock);
//document.getElementById('detailsSpace').innerHTML = "Loading...";
//document.getElementById('detailsSpace').innerHTML = thisCompanyMarkupBlock;
jQuery("#detailsSpace").html(thisCompanyMarkupBlock);
}
}
Instead of using .html(), you can use clear and append, yo ensure your container is empty, something like:
jQuery("#detailsSpace").empty(); // Before while
while ([...]){
[...]
jQuery("#detailSpace").append(thisCompanyMarkupBlock); // Instead of html()
}
Found the problem - there was another function where because of a loop it was keeping the previous set of returned HTML when it got reprocessed. The jquery.empty() function was put in at the right place along with declaring the string null again, fixed now.
I've scrolled through most of the questions in stack overflow and also Google and tried out a bunch of codes but still can't seem to get my code to work!
So what I'm trying to do is to get some text and scripts via Ajax and insert them onto a div, however, the inline jQuery doesn't seem to work. The text can be very long, so what I wanted to do was add a preview of the text, and when the user clicked a "See more" link, the jQuery toggled the longer text to display and hide the preview.
Here is my code that inserts text into the document;
JSON returned from Ajax
if (resp['marker'].length > 0) {
htmltext = '<h5>Markers<a class="pull-right" onclick="seeall(\'marker\')">See all</a></h5><hr>';
for (var i = 0; i < resp['marker'].length; i++) {
htmltext += '<p><a>'+resp['marker'][i]['title']+'<a class="label label-warning"> > Go to marker</a></a></p>';
htmltext += '<p id="marker-prev'+i+'"><span>'+resp['marker'][i]['advertisement'].substring(0,50)+'</span><a onclick="$(\'#marker-all'+i+'\').toggle();$(\'#marker-prev'+i+'\').toggle()"> More </a></p>';
htmltext += '<p style="display:none" id="marker-all'+i+'"><span>'+resp['marker'][i]['advertisement']+'</span><a onclick="$(\'#marker-all'+i+'\').toggle();$(\'#marker-prev'+i+'\').toggle()"> Less </a></p>';
htmltext += '<p><span>'+resp['marker'][i]['catagory']+'</span></p>';
}
htmltext += '<hr>';
$('#markerssr').show();
$('#markerssr').html(htmltext);
}
funny thing is, several lines down, THIS code works;
JSON returned from Ajax call
if (resp['corp'].length > 0) {
htmltext = '<h5>Businesses<a class="pull-right" onclick="seeall(\'corp\')">See all</a></h5><hr>';
for (var i = 0; i < resp['corp'].length; i++) {
htmltext += '<p><a>'+resp['corp'][i]['name']+'</a><a class="label label-warning"> > Go to business</a></p>'
htmltext += '<p id="corp-prev"><span>'+resp['corp'][i]['description'].substring(0,50)+'</span><a onclick="$(\'#corp-all\').toggle();$(\'#corp-prev\').toggle()"> More </a></p>';
htmltext += '<p style="display:none" id="corp-all"><span>'+resp['corp'][i]['description']+'</span><a onclick="$(\'#corp-all\').toggle();$(\'#corp-prev\').toggle()"> Less </a></p>';
htmltext += '<p><span>'+resp['corp'][i]['address']+'</span><span>'+resp['corp'][i]['email']+'</span></p> ';
}
htmltext += '<hr>';
$('#businessessr').show();
$('#businessessr').html(htmltext);
}
Sorry my code is horribly formatted, but I am on a deadline.
The first thing I see (but it probably is nothing new), is that there are different ID's called from within the inline jQuery.
$(\'#marker-all\').toggle() VS $(\'#corp-prev\').toggle().
Also, are you sure there is only 1 #marker-all on the page? jQuery will stop searching after it has found the first ID.
When you run the following code in the browser console:
$('#marker-all').length
Does it output 1? Or 0?
Readers,
Background:
I have an html page with a submit button on it. This button, when clicked goes to the servlet and fetches the first 10 rows of data from my database. I then get this data back to my javascript via an ajax call. That all works. I can see the data in json format in my javascript.
Problem:
After the data is returned, it goes to a method called generate the table. But the table never shows on my html page. I tried to follow this demo approach. How can I draw a table after this method is being called? The <p></p> approach in the demo didn't work in the link I provided either.
function createTable(result)
{
var length = result.jsonList.length;
var tablecontents = "";
console.log(length);
tablecontents="<table>";
for(var i = 0; i < length; i++)
{
tablecontents += "<tr>"
tablecontents += "<td>" + result.jsonList[i].Id + "</td>"
tablecontents += "</tr>"
console.log(result.jsonList[i].Id);
}
tablecontents="</table>";
document.getElementById("tablespace").innerHTML = tablecontents;
}
Okay, so the console.log part gives me the following output:
1
2
3
4
5
6
7
8
9
10
So I have the data. However, no database is being drawn on my htmlpage. Here is the relevant HTML code:
<body>
<form id = "submitTable" method="post">
<center><input id="getTable" type="button" value="Table"></center>
<div id="tablespace"></div>
</form>
</body>
I point out the button calls the ajax. There is no need to show you my ajax call because that works. It calls my createTable function when it gets the data back from the servlet. I know it is working because I can print the unique database id's with the console.log. However, the
document.getElementById("tablespace").innerHTML = tablecontents
is not working? Stranger is that when I run and view source on chrome. I see no error with the html. So I don't know what I am doing wrong?
tablecontents+="</table>" inplace of tablecontents="</table>"
Here's the problem:
tablecontents="</table>";
document.getElementById("tablespace").innerHTML = tablecontents;
You set "tablecontents" to be only the </table> tag. Should be:
tablecontents += "</table>"; // += not =
document.getElementById("tablespace").innerHTML = tablecontents;
How can I copy an entire div to a popup window?
What I`m trying to do:
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript' />\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
text += $("#divDadosBasicos").html($(querySelector).html());
text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n/body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
I dont know if this is the better way to do it. If you think/know a easier way to do it, please share
Thanks in advance!
Fix some of these errors and it will work fine
Script tag is not closed properly
body tag not closed properly
querySelector is not defined. (I am commenting that portion)
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript'></script>\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
//define querySelector
//text += $("#divDadosBasicos").html($(querySelector).html());
//text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n</body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
You could use a Jquery Modal Popup
http://jqueryui.com/demos/dialog/
Check it out, it has the functionality that you need.
It has several events you can tweak to modify the data.
Just tested this, and the code seems to be working just fine as long as querySelector is defined, and it's in a document.ready function and you are testing this on an actual webserver (like WAMP/LAMP etc.). It will not work in places like jsFiddle etc.