I want to know whether there is an input mand in JavaScript like "cin>>" in C++ or the input in old Basic... because I need to ask the user to enter a word or a number on a web page and want to save that input into a variable and then print that variable using document.write(). There's the option of inputting through an input box in HTML and getting that input using document.getElementById and then writing that with the innerHTML element into a paragraph tag, but I just want to know if there's a simpler version available in js. Thanks.
I want to know whether there is an input mand in JavaScript like "cin>>" in C++ or the input in old Basic... because I need to ask the user to enter a word or a number on a web page and want to save that input into a variable and then print that variable using document.write(). There's the option of inputting through an input box in HTML and getting that input using document.getElementById and then writing that with the innerHTML element into a paragraph tag, but I just want to know if there's a simpler version available in js. Thanks.
Share Improve this question edited Sep 8, 2017 at 21:23 asked Sep 8, 2017 at 17:13 user8549160user8549160 4-
5
prompt? But you don't want to use
document.write
. – Teemu Commented Sep 8, 2017 at 17:16 -
var userInput = prompt("Please enter a value:")
to save the user's input into a variable. Then you can output that value in a myriad of different ways. – mhodges Commented Sep 8, 2017 at 17:19 -
Do note that
prompt()
will return the user's entry as a string and you will need to useparseInt()
orparseFloat()
if you intend to use the value as a number. – Corey Ogburn Commented Sep 8, 2017 at 17:29 - Great! Thank you for your answers, it's been very helpful. This is how the piece of code I was looking for finally looks like: <!DOCTYPE html> <html> <body <script> var userInput = prompt ("Enter your name: ") document.write(userInput) </script> </body> </html> – user8549160 Commented Sep 9, 2017 at 9:19
2 Answers
Reset to default 3I don't think there is anything exactly like that in JS. But here is an example of the prompt function in Javascript.
https://www.w3schools./jsref/tryit.asp?filename=tryjsref_prompt
Node JS have readline interface to do this, you can read it hear: https://nodejs/api/readline.html
With this document, you can input from console like c++ or java. The code example:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();
});
For more practice case, you can visit this video: https://www.youtube./watch?v=jXaBeZ19RB4&t=329s
JS don't have friendly console input interface.