There are multiple ways you can get user input in javascript.
- Using
prompt(). Prompt is a function will allows you to bring up a dialogue box which from that you can enter text, numbers, etc... The text you enter as an argument will act as the heading of the pop-up alert.
Take a look at the snippet below for an example:
let input = prompt("Enter a number:"); // Input in string format
let triple = input * 3; // Convert string to integer by using * operation
console.log(triple);
- Another way you can retrieve user input is through HTML input elements. There are a number of different types of input elements which you can use such as password, number, date, text, etc... For your question, you would want to use a
number input. You can create a number input like so in HTML:
<input type="number" id="number" value="0" />
Here the type attribute specifies that we will be entering a number as our input. The id attribute provides us with a way to refrence this input element in javascript so we can latter retrieve the number enter into it. And the value attribute is an optional attribute which specifies the default value of the input box.
When working with input boxes you need to specify when javascript should check the input box for a value. You can do this by adding an event listener so that your javascript will run a section of code everytime the user enters a number. Here is an example of adding an event listener to our number input box so that it triggers which the number in it changes:
document.getElementById('number').addEventListener('keyup', function(e) {/* do code */});
In the above line, we are referencing the input box via its id (number) and adding an input event listener to it.
Using this event listener we can then use the this keyword inside the function to refer to the input box itself. This allows us to do this.value to get the value of the number entered. Here I have also use e.keyCode to detect which key was pressed. If the keyCode is equal to 13 (ENTER) then the code will log the result, otherwise (else) it will do nothing.
See working example below:
document.getElementById('number').addEventListener('keyup', function(e) {
if(e.keyCode == 13) { // Check if enter key pressed
let triple = this.value * 3; // Get value of text box using this.value
console.log(triple);
}
});
<input type="number" id="number" value="0" />
document.selectorand target desired input and get value from it.