JavaScript: read text from an input
prompt, HTML input.value and turning text into a number. Cancel returns null.
All lessons · JavaScript lessons: learn from scratch
Ask with prompt
prompt opens a small window in the browser and returns the text. Cancel gives null. The result is always text. If you need a number, write Number, or "12" + "34" becomes "1234".
let ad = prompt("Adınızı daxil edin:");
if (ad === null) {
console.log("İmtina edildi.");
} else {
console.log("Salam, " + ad + "!");
}
let a = Number(prompt("Birinci ədəd:"));
let b = Number(prompt("İkinci ədəd:"));
console.log(a + b);Read an HTML input
The text in a page box is in .value. Read it when the button is clicked and show it with textContent. On a form submit, call preventDefault so the page does not reload.
<input id="adInput" type="text">
<button id="gosterBtn">Göstər</button>
<p id="netice"></p>
<script>
const adInput = document.getElementById("adInput");
const netice = document.getElementById("netice");
document.getElementById("gosterBtn").addEventListener("click", function () {
netice.textContent = "Salam, " + adInput.value + "!";
});
</script>readline in Node.js
Outside the browser, in a terminal, readline asks a question. The answer arrives in a function. Call rl.close() at the end, or the program keeps waiting. For a page lesson, prompt and an HTML input are enough.
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question("Adınız: ", function (ad) {
console.log("Salam, " + ad + "!");
rl.close();
});Questions
What does prompt return? Text. null if Cancel is pressed.
Why do two numbers stick together? They are still text. Convert with Number(), then add.
Where is the text of an HTML box? input.value. To show it, change another element's textContent.
Why does a form reload the page? submit does that. event.preventDefault() stops the reload.