JavaScript – Getting User Input

To get user input, you must understand the getElementById() function.

Getting user input

JavaScript can get the input value from an <input> element if it has an id attribute.

Example:

<input id="word">
<button id="done" onclick="go()">Read Word</button>
<script>
function go(){
  var w = document.getElementById('word').value;
  console.log("You typed this word: " + w);
}
</script>

This example defines an object d as the input element using getElementById().

Then it uses the value attribute to read the text from the input element.

This part of the code is equal to the text from the “word” element:

document.getElementById('word').value

That code equals the text (string data type) from the input box.

You can use that anywhere that a string can be used.

You could display the user’s text in another element on the page:

w = document.getElementById('word').value;
document.getElementById('text').innerHTML = w;