I have an ASPX page with hidden iframe.
I'm trying to: on button click load another page into that hidden iFrame and print it's content:
$("#shareButtonPrint").click(function () {
$("#PrintFrame").attr('src', '/ProtocolPrintPage.aspx?g=1');
$("#PrintFrame").ready(function () {
window.frames['PrintFrame'].print();
});
});
but the code above doesn't work.
It works only when I load the iframe on main page load:
$("#PrintFrame").attr('src', '/ProtocolPrintPage.aspx?g=1');
$("#shareButtonPrint").click(function () {
//$("#PrintFrame").attr('src', '/ProtocolPrintPage.aspx?g=1');
window.frames['PrintFrame'].print();
});
How can I load the iframe on button click ?
This is likely due to the iframe not yet being loaded when you're trying to print it
Perhaps try using load
instead of ready
Check out my example here
http://jsfiddle.net/andyw_/umYkV/451/
Only tested in latest chrome + IE8-10.
Also note that load
is deprecated
http://api.jquery.com/category/deprecated/
The new way of doing it is on('load', fn)
<button id='click'>click me</button>
<iframe style="display:none" id='toPrint' src='' /></iframe>
$(function(){
$('#click').on('click', function(){
$('#toPrint').attr('src', 'https://fiddle.jshell.net/doiks14/umYkV/451/show/');
$('#toPrint').load(function() {
console.log(window.frames['toPrint']);
try {
window.frames['toPrint'].print();
} catch (e) {
console.log(e);
try {
window.frames['toPrint'].contentWindow.print();
} catch (e) {
console.log(e);
}
}
});
});
});