Don't use document.writeln
and document.write
after the page has been loaded (or, in most cases, at all). If you use them once the page is loaded, they implicitly open the page again — wiping out all of its contents and replacing them with the new content you provide.
To add to the DOM, use DOM methods:
Separately, to get the value of an input
, you use its .value
property.
Here's your example using insertAdjacentText
:
function getval() {
const submittedValue = document.getElementById('number').value;
document.body.insertAdjacentText("beforeend", submittedValue);
}
<label for="num">Enter the number</label>
<input type="number" name="num" id="number">
<button onclick="getval()">Submit the number</button>
Or more likely, you want to add a p
or similar to wrap it in:
Or creating an element and appending it, so all the numbers don't join up when you use the button more than once:
function getval() {
const submittedValue = document.getElementById('number').value;
const p = document.createElement("p");
p.textContent = submittedValue;
document.body.appendChild(p);
}
<label for="num">Enter the number</label>
<input type="number" name="num" id="number">
<button onclick="getval()">Submit the number</button>
Finally, I strongly recommend not using onxyz
-attribute style event handlers. Instead, use addEventListener
:
document.getElementById("the-button").addEventListener("click", () => {
const submittedValue = document.getElementById('number').value;
const p = document.createElement("p");
p.textContent = submittedValue;
document.body.appendChild(p);
});
<label for="num">Enter the number</label>
<input type="number" name="num" id="number">
<button id="the-button">Submit the number</button>