There are 5 ways you can take user input in JavaScript:
P.S. -> read this article if you want to double your salary as a programmer
prompt
prompt is a JavaScript command that shows a dialog box where user can enter some data. This data is then stored into a variable that can be used later in your program.
<script>
let data = prompt("Enter some data:");
</script>
You can also prefill the dialog box with some default data like this:
<script>
let data = prompt("Enter some data:", "Default data");
</script>
confirm
confirm is a JavaScript command that shows a dialog box and only allows user to press wither “OK” or “Cancel”. If the user pressed “OK” then this method returns true. If the user pressed “Cancel” then this method returns false.
<script>
let didPressOk = confirm("Do you agree?");
if (didPressOk === true) {
// do something when user agrees
} else {
// do something when user disagrees
}
</script>
input
input is an HTML tag that behaves as an input field where user can enter data. Then you can use JavaScript to read the values from that field like this:
<input id="user-data" />
...
<script>
function readData() {
const input = document.querySelector('user-data');
const data = input.value;
// use data here
}
</script>
textarea
textarea is an HTML element similar to input but it supports multi-line data format.
<textarea id="user-data"></textarea>
...
<script>
function readData() {
const textarea = document.querySelector('user-data');
const data = textarea.value;
// use data here
}
</script>
div
You probably don’t know this but div element can be turned into editable field that your users can type into. And then you can read this data and use it later in your program.
The key is in using HTML element attribute contentEditable property and set it to true.
Also, you have to use .innerText property to get the values from this HTML element.
<div
id="user-data"
contentEditable="true"
>
here is an optional default content
</div>
...
<script>
function readData() {
const textarea = document.querySelector('user-data');
const data = textarea.innerText;
// use data here
}
</script>
PRO TIP: you can also use this trick on other HTML elements like li, span, a, h1, and others.
P.S. -> read this article if you want to double your salary as a programmer
TAGS: how to get user input in javascript, user input javascript, how to take input in javascript, javascript user input, how to get input in javascript, javascript prompt for input,