-1

I am new to JavaScript, and can't get this problem solved

Error : btn.addEventListener is not a function

It works when I use query selector, but not when I getElementByClassName

HTML

<input type="text" class="amount">
     <select>
                <option class="option" value="1">Good</option>
                <option class="option" value="2">Ok</option>
                <option class="option" value="3">Bad</option>
            </select>
 <button class="btn"> Calculate </button>

JavaScript

const amount = document.getElementsByClassName('amount');
const btn = document.getElementsByClassName('btn');

btn.addEventListener('click', a());

function a() {
  alert('100');
}

The alert fires off on the load of the window!

Word Rearranger
  • 1,306
  • 1
  • 16
  • 25

1 Answers1

0

You're accessing HTML elements before they are available, to avoid that use $(document).ready.

document.getElementsByClassName is an array.

addEventListener function accepts function defination, you are calling function addEventListener('click',a()). It should be addEventListener('click',a)

$( document ).ready(function() {


  const amount = document.getElementsByClassName('amount')[0];
  const btn = document.getElementsByClassName('btn')[0];

  btn.addEventListener('click', a);

  function a() {
    alert('100');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="amount">
<select>
    <option class="option" value="1">Good</option>
    <option class="option" value="2">Ok</option>
    <option class="option" value="3">Bad</option>
</select>
<button class="btn"> Calculate </button>
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29