Copy textbox content to div page and print
I need to copy the content of a textarea to a div and then print the page including the new value in the div.
<textarea id="np01" rows="1" autofocus></textarea>
So I typed some content into a text box.
$("#btnPrint").click(function(){
givemevars();
$("#ph1").html(np01);
window.print();
});
function givemevars(){
var np01 = $('#np01').val();
}
Problem:
-
Once clicked, the
#btnPrint
div#ph1
has not only the value but also the background of the associated textbox (#np01
). I only need the value, i.e. Text. -
In the preview (
window.print()
) window, the div is#ph1
empty, i.e. without any new content inside.
Any help?
source to share
When you declare a variable with var
within a function, it is local only to that function. Instead, you should return the value from givemevars()
and use this:
$("#btnPrint").click(function(){
var np01 = givemevars(); //now it local to the click callback function
$("#ph1").html(np01);
window.print();
});
function givemevars(){
// this sends the value back to where this function was called (above)
return $('#np01').val();
}
Another way to do this is to declare var outside of functions and then set / use it inside them. This is generally bad practice, but try to avoid using globals whenever possible. For completeness, here's what it would look like:
var np01;
$("#btnPrint").click(function(){
givemevars();
$("#ph1").html(np01);
window.print();
});
function givemevars(){
// note the lack of "var", this way it sets an existing variable
// instead of creating a new (local) one
np01 = $('#np01').val();
}
source to share
change your code so that your function will givemevars
return the textarea value and store it in a variable used in the click event
$("#btnPrint").click(function(){
var value = givemevars();
$("#ph1").html(value);
window.print();
});
function givemevars(){
return $('#np01').val();
}
source to share
Yours np01
should be empty in the click event. Because ... you don't put return
in your original function, that means you made it void
. Therefore, you need to use a static variable and use it in the function to store data, which is not recommended in this case.
You can enter html or text via .html()
or .text()
. This is your call.
Try it and edit your code. I will give you an example and working code.
$("#btnPrint").click(function(){
//givemevars();
//$("#ph1").html(np01);
//window.print();
var content = giveMeVars();
$('#print').text(content);
});
//function givemevars(){
// var np01 = $('#np01').val();
//}
function giveMeVars() {
return $('textarea').val();
}
button, textarea {
vertical-align:top;
}
textarea {
width:400px;
height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnPrint">Print this</button>
<textarea id="np01" rows="1" autofocus></textarea>
<h3>Print result...</h3>
<div id="print"></div>
source to share