Accepting User Input

So, after all of this, how do you do a console input operation? I mean, console.log() displays to the console, but what command waits for the user to enter information into the program?
What good is this language if there is no way to make it interactive?
There should be a course on how to do THAT.

1 Like

Hey there,

JavaScript can indeed be used to grab inputs for a user. This forum, for example, uses JavaScript to handle how the text you write into a textbox gets posted to a thread.

We can use JavaScript to grab the text you wrote in your post and print it to the console. Try opening up the developer console. On Google Chrome, you can go to View, then Developer, then JavaScript Console, or press option-command-J on the keyboard (or on windows control-shift-j). Then run the following JavaScript:

let p = document.getElementsByTagName('p');

This looks at the HTML for the current web page, grabs all the <p> (paragraph) tags, and saves it to an array-like object called an HTMLCollection.

Let’s take a look at the 4th <p>, at index 3:

let yourPost = p[3];

Now let’s play with it a bit:

yourPost.innerText = 'Look at what JavaScript can do!';

Hope this helps!
–Ben

1 Like

That didn’t really help. That’s HTML, which I know USES JavaScript, but it’s not JavaScript itself.
I’m looking for means outside of HTML, strictly JavaScript.

Could you write a simple code that asks for a name and an age (number) and then uses the user input (not the programmer’s) to fill in a name with their input and use the number for their name?

1 Like

When running JavaScript in the browser, there isn’t anything like console.getInput(). However, window.prompt() can be used to get input.

Open up the developer console again so you can run some JavaScript. You can write something like:

var person = prompt('What is your name'?);
console.log('Hello ' + person);

If you’re running JS in a CLI (command line interface) and not in a browser, Node.js has its own built-in functions for getting input from a command line. That’s a bit outside the bounds of what I can help you with, but you can find tutorials online on how to use the CLI and getting set up with Node.

2 Likes

Ok. Thank you. I will try that. It may be what I need.

1 Like