To take user input in JavaScript, there are multiple ways. One of the most common ways to take input is through forms. A form is an HTML element that contains input elements such as text boxes, dropdowns, checkboxes, and more.
To get the data entered in the form, we can use the value
property of the input element. We can get a reference to the input element using the document.querySelector()
method.
Here is an example of a form with a text input and a submit button:
131 chars6 lines
In the JavaScript, we can add an event listener to the form's submit button to get the data entered in the form. Here is an example:
index.tsx315 chars9 lines
In the example above, we added an event listener to the form element that listens for a 'submit' event. When the user clicks the submit button, the event listener function is called. The first line of the function is event.preventDefault()
, which prevents the form from submitting and refreshing the page.
We then get a reference to the input element using its ID (#nameInput
), and get the value of the input using the value
property. Finally, we log a message to the console that includes the entered name.
gistlibby LogSnag