Can you print a page in a function being defined in javascript? - javascript

I have (had 2 years ago lol) been working on a web page that prints everything on it, and need to define a function that gets a value, replaces the text box with the value, hides the print button, and prints the page.
<!DOCTYPE HTML>
<HTML>
<head>
<title>KB documents</title>
</head>
<body>
<style>
body {
text-align:center;
}
</style>
<div id="hidden">
<textarea cols="125" rows="30" id="value"></textarea>
</div>
<button id="button" onclick="print()">print document</button>
<script>
function print() {
var value = document.getElementById("value").value;
document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
document.getElementById("button").style.display = "none";
window.print()
}
</script>
</body>
</html>
It works perfectly--with the exception of printing the page, the most important part.
Thanks in advance.

Your function print on the top level is overwriting the built-in window.print. Use a different variable name so that window.print does not get reassigned:
<button id="button" onclick="doPrint()">print document</button>
<script>
function doPrint() {
var value = document.getElementById("value").value;
document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
document.getElementById("button").style.display = "none";
window.print()
}
But it would be better to avoid inline handlers, they have way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with addEventListener instead.
document.querySelector('#button').addEventListener('click', () => {
var value = document.getElementById("value").value;
document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
document.getElementById("button").style.display = "none";
window.print()
});

Related

JavaScript function only works after page reload

I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>

How can I create an unordered HTML list using JavaScript (without strange behaviour)?

I am trying to capture time from a stopwatch within a browser and display the times (laps) below. To do this, I am intending to create an unordered list from an array within a JavaScript file.
Here is the JS:
laps = []:
function show() {
$time = document.getElementById('time');
document.getElementById("capture").setAttribute("disabled","disabled"); // disable capture button until start
update();
}
function update() {
$time.innerHTML = formatTime(time());
displayLaps();
}
function displayLaps() {
if (laps == "" || laps.length == 0) {
return false; // stop the function if the value is empty
}
var inner = `Lap ${lap_count} :${formatTime(laps[lap_count-1])}`;
document.getElementById("laps").innerHTML += '<li>' + inner + '</li>';
}
And the associated html:
<!doctype html>
<html lang="en">
<head>
</head>
<body onload="show()">
<div>Time: <span id="time"></span></div>
<button onclick="onStart()" id="start" style="width:150px">Start</button>
<button id="capture" style="width:150px">Capture</button>
<div id="laps"><ul></ul></div>
<script src=".\stopwatch.js"> </script>
</body>
</html>
I am getting peculiar behaviour though. It seems that the += operator on the last line of code keeps adding rows that display the last array vaue (see below), whereas replacing this with a simple = operator just creates a single row that is then replaced every time a new lap value is added to the array.
I'm obviously missing something, but would appreciate some guidance, if possible.
Many thanks!

Open popup in Javascript

I have a js rendered in HTML which would give a preview of the form. The code is functioning correctly but it gives me the output on the same page rather i want to open it in a pop-up window. I have tried using window.open () with no luck. Could you please help me out in how i can use window.open() for the below. The button ID is preview. When the button is clicked it executes a function similar to below
$("#preview").click(function() {
$("#formpreview").delete();
var fieldSet = ...................});
You can populate the html in the child window using the below example:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input type="button" id="launch" value="Launch Child Window"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
var btnLaunch = document.getElementById("launch");
btnLaunch.onclick = function () {
var childWindow = window.open("", "", "height=500, width=500");
var html = "";
var theVariable = "Conent in Child Window";
html += "<p>" + theVariable + "</p>";
childWindow.document.body.innerHTML = html;
}
Store the popup as a variable, then set the popup's HTML to whatever you need.
$("#preview").click(function() {
var myWindow = window.open("", "Popup", "width=300, height=500");
myWindow.document.write("<html>This is where your content goes</html>");
});

How to change an html tag with Javascript? [duplicate]

This question already has an answer here:
dynamically changing HTML tag
(1 answer)
Closed 9 years ago.
I want to display the text from a string into an HTML tag without moving to next page and display it.
<body>
<div>
<label id="lbl1">Label </label>
<button id="btn1" onclick="display()">Click </button>
<script>
function display() {
var str="Hello World";
document.write(str);
}
</script>
</div>
</body>
How do I edit the contents of the label tag?
Common …
document.getElementById('lbl1').innerHTML = str;
function display() {
var str="Hello World";
var label = document.getElementById('lbl1');
label.innerHTML = str;
}
<body>
<div>
<label id="lbl1">Label </label>
<button id="btn1" onclick="display()">Click </button>
<script>
function display() {
var str="Hello World";
var label = document.getElementById("lbl1");
label.innerText = str;
}
</script>
</div>
</body>
When you click the button, the function display() is run, and the label tag's text is changed to "Hello World".
Use document.getElementById("lbl1").innerHTML = display(); and add a return statement inside the function:
function display()
{
var str="Hello World";
return str;
}
You edit the contents in a similar manner: document.getElementById("lbl1").innerHTML = "New content...";.
You could also modify your display() function a little bit to get the desired result:
function display()
{
var str="Hello World";
var label = document.getElementById("lbl1");
label.innerHTML = str;
}
Another way:
window.onload = function()
{
var button = document.getElementById("btn1");
button.onclick = function()
{
document.getElementById("lbl1").innerHTML = "Hello World";
}
}
The last way is the most desired and it's the best to put JavaScript code inside another file and attach it via the src attribute of the script element.
Let's provide a complete example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<label id="lbl1">Label </label>
<button id="btn1">Click </button>
</body>
</html>
Then inside the JavaScript file you just register various events:
//JavaScript
window.onload = function() //You have to ensure that everything has loaded
{
var button = document.getElementById("btn1");
button.onclick = function()
{
document.getElementById("lbl1").innerHTML = "Hello World";
}
}
It's generally considered the best way to register events in a separate JavaScript file because of performance and maintenance simplicity gains. You can read more about it here.

How can I change global variables in javascript?

My html page displays a button that calls a function when it is clicked. I checked to make sure that the button works properly by displaying a message when clicked and it worked. I created this function to change the global varible but when I click another button on my html page to show the value of the varibles the varibles have not changed to the value I set them using my function. Could someone find the problem in my code below?
var a = 5;
var b = 16;
var c = 27;
function reset(){
a = 0;
b = 0;
c = 0;
}
My html code to call the function:
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Reset Variables" style="width:250px;height:50px" onclick="reset()" >
</form>
</html>
Javascript code to show the variables:
function display(){
document.write("A is equal to " + a + "<br/>");
document.write("B is equal to " + b + "<br/>");
document.write("C is equal to " + c );
}
Html to display the variables
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Show Variables" style="width:250px;height:50px" onclick="display()" >
</form>
</html>
change the function name to reset_vars or anything else. reset() is in-built DOM function used for resetting forms.
http://www.w3schools.com/jsref/met_form_reset.asp
There won't be any conflict when a global variable is used inside a function unless a local variable is defined. in such case, use window.variable_name to access global variable.
That can`t work, because you are asserting that variables in function scope. But your variables are currently stored in global scope (window), so this code will work:
var a = 5;
function reset() {
console.log(window.a); // 5
window.a = 10;
}
reset();
console.log(a); // 10

Categories