How to Pass HTML Values to a JavaScript Function?

Estimated read time 1 min read

You can pass values from HTML elements to a JavaScript function in several ways:

  1. Through the onclick attribute:
<button onclick="myFunction(this.value)">Click me</button>

<script>
  function myFunction(value) {
    console.log(value);
  }
</script>
  1. By getting the value using document.querySelector:
<input type="text" id="inputField">
<button onclick="myFunction()">Click me</button>

<script>
  function myFunction() {
    const inputValue = document.querySelector("#inputField").value;
    console.log(inputValue);
  }
</script>
  1. By passing the element as a parameter in an event handler:
<input type="text" id="inputField">
<button id="myButton">Click me</button>

<script>
  const button = document.querySelector("#myButton");
  button.addEventListener("click", function(event) {
    const inputValue = document.querySelector("#inputField").value;
    console.log(inputValue);
  });
</script>

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply