You can get the value from an input field in JavaScript by first selecting the input element, and then accessing its value property. Here are a few examples:

Using the getElementById method:

<input type="text" id="myInput">
<script>
  var input = document.getElementById("myInput");
  var value = input.value;
  console.log(value);
</script>

Using the querySelector method:

<input type="text" class="myInput">
<script>
  var input = document.querySelector(".myInput");
  var value = input.value;
  console.log(value);
</script>

Using the getElementsByName method:

<input type="text" name="myInput">
<script>
  var input = document.getElementsByName("myInput")[0];
  var value = input.value;
  console.log(value);
</script>

In all examples, value will contain the current value of the input field.

You can also retrieve the value of the input field when the input event is triggered by adding an event listener on the input element

<input type="text" id="myInput">
<script>
  var input = document.getElementById("myInput");
  input.addEventListener("input", function() {
    console.log(this.value);
  });
</script>

In this example, the function passed to the addEventListener will be called every time the value of the input field changes and will output the current value of the input field.

Also Read:

Categorized in: