How to Pass a Button Value from HTML to a JavaScript Function?

Estimated read time 1 min read

You can pass a button value from HTML to a JavaScript function in several ways:

  1. By setting the value of the button as an attribute:
<button value="Button 1" onclick="myFunction(this.value)">Button 1</button>
<button value="Button 2" onclick="myFunction(this.value)">Button 2</button>

<script>
  function myFunction(value) {
    console.log(value);
  }
</script>
  1. By setting the text content of the button as the value:
<button onclick="myFunction(this.textContent)">Button 1</button>
<button onclick="myFunction(this.textContent)">Button 2</button>

<script>
  function myFunction(value) {
    console.log(value);
  }
</script>
  1. By using a data attribute:
<button data-value="Button 1" onclick="myFunction(this.getAttribute('data-value'))">Button 1</button>
<button data-value="Button 2" onclick="myFunction(this.getAttribute('data-value'))">Button 2</button>

<script>
  function myFunction(value) {
    console.log(value);
  }
</script>

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply